branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>lazmoreira/go-todo-server<file_sep>/go.mod
module github.com/lazmoreira/go-todo
go 1.14
require (
github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a
github.com/gorilla/mux v1.7.4
go.mongodb.org/mongo-driver v1.3.4
)
<file_sep>/README.md
# go-todo-server
Simple todo app
<file_sep>/middleware/middleware.go
package middleware
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/go-http-utils/headers"
"github.com/gorilla/mux"
"github.com/lazmoreira/go-todo/models"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const connectionString = "mongodb+srv://todoUser:<EMAIL>/test?retryWrites=true&w=majority"
//const connectionString = "mongodb://0.0.0.0:27017/admin"
const dbName = "TodoDB"
const collectionName = "Todos"
var collection *mongo.Collection
func init() {
clientOptions := options.Client().ApplyURI(connectionString)
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection = client.Database(dbName).Collection(collectionName)
fmt.Println("Collection instance created!")
}
// GetAllTask get all task route
func GetAllTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
payload := getAllTask()
json.NewEncoder(w).Encode(payload)
}
// CreateTask create task route
func CreateTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
w.Header().Set(headers.AccessControlAllowMethods, "POST")
w.Header().Set(headers.AccessControlAllowHeaders, "Content-Type")
var task models.ToDoList
_ = json.NewDecoder(r.Body).Decode(&task)
insertOneResult := insertOneTask(task)
if oid, ok := insertOneResult.InsertedID.(primitive.ObjectID); ok {
task.ID = oid
}
json.NewEncoder(w).Encode(task)
}
//TaskComplete task complete route
func TaskComplete(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
w.Header().Set(headers.AccessControlAllowMethods, "PUT")
w.Header().Set(headers.AccessControlAllowHeaders, "Content-Type")
if r.Method == "PUT" {
params := mux.Vars(r)
json.NewEncoder(w).Encode(taskComplete(params["id"], r))
} else {
return
}
}
//UndoTask task complete route
func UndoTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
w.Header().Set(headers.AccessControlAllowMethods, "PUT")
w.Header().Set(headers.AccessControlAllowHeaders, "Content-Type")
params := mux.Vars(r)
undoTask(params["id"])
json.NewEncoder(w).Encode(params["id"])
}
//DeleteTask task complete route
func DeleteTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
w.Header().Set(headers.AccessControlAllowMethods, "DELETE")
w.Header().Set(headers.AccessControlAllowHeaders, "Content-Type")
if r.Method == "DELETE" {
params := mux.Vars(r)
deleteOneTask(params["id"])
json.NewEncoder(w).Encode(params["id"])
} else {
return
}
}
//DeleteAllTask task complete route
func DeleteAllTask(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headers.ContentType, "application/x-www-form-urlencoded")
w.Header().Set(headers.AccessControlAllowOrigin, "*")
count := deleteAllTask()
json.NewEncoder(w).Encode(count)
}
func getAllTask() []primitive.M {
cur, err := collection.Find(context.Background(), bson.D{{}})
if err != nil {
log.Fatal(err)
}
var results []primitive.M
for cur.Next(context.Background()) {
var result bson.M
e := cur.Decode(&result)
if e != nil {
log.Fatal(e)
}
results = append(results, result)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
cur.Close(context.Background())
return results
}
func insertOneTask(task models.ToDoList) *mongo.InsertOneResult {
insertResult, err := collection.InsertOne(context.Background(), task)
if err != nil {
log.Fatal(err)
}
fmt.Println("New task added", insertResult.InsertedID)
return insertResult
}
// task complete method, update task's status to true
func taskComplete(task string, r *http.Request) models.ToDoList {
var initialTask models.ToDoList
id, _ := primitive.ObjectIDFromHex(task)
filter := bson.M{"_id": id}
err := collection.FindOne(context.Background(), filter).Decode(&initialTask)
if err != nil {
log.Fatal(err)
}
update := bson.M{"$set": bson.M{"status": !initialTask.Status}}
_, err = collection.UpdateOne(context.Background(), filter, update)
if err != nil {
log.Fatal(err)
}
var updatedTask models.ToDoList
err = collection.FindOne(context.Background(), filter).Decode(&updatedTask)
if err != nil {
log.Fatal(err)
}
return updatedTask
}
// task undo method, update task's status to false
func undoTask(task string) {
fmt.Println(task)
id, _ := primitive.ObjectIDFromHex(task)
filter := bson.M{"_id": id}
update := bson.M{"$set": bson.M{"status": false}}
result, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Println("modified count: ", result.ModifiedCount)
}
// delete one task from the DB, delete by ID
func deleteOneTask(task string) {
fmt.Println(task)
id, _ := primitive.ObjectIDFromHex(task)
filter := bson.M{"_id": id}
d, err := collection.DeleteOne(context.Background(), filter)
if err != nil {
log.Fatal(err)
}
fmt.Println("Deleted Document", d.DeletedCount)
}
// delete all the tasks from the DB
func deleteAllTask() int64 {
d, err := collection.DeleteMany(context.Background(), bson.D{{}}, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Deleted Document", d.DeletedCount)
return d.DeletedCount
}
| 8fd61f9c3c42f56753dead1c3c086b92beeaaa5d | [
"Markdown",
"Go Module",
"Go"
] | 3 | Go Module | lazmoreira/go-todo-server | baee21b6cd2a74a903a22b55282da5097834fe4e | 59fbaeed07b0cdf148974f203335498af856ea2b |
refs/heads/master | <file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Master Module
* Controller
*
* Using Atmega1284
*/
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
int throttle_input = 0x00;
int turn_input = 0x00;
unsigned char adc_translation = 0x00;
unsigned char is_automatic = 0x00;
extern unsigned char bt_data;
enum Joysticks_SM {Joysticks_Init, Joysticks_Get_Turn, Joysticks_Get_Throttle} joysticks_state;
enum Button_SM {Press1, Wait1, Press2, Wait2} button_state;
unsigned char Translate(int x){
if (x < 500){ // Left or Down
return 1;
}
else if (x < 600){ // Middle
return 2;
}
else { // Right or Up
return 3;
}
}
void Joysticks_Tick(){
if (is_automatic){return;}
switch(joysticks_state){ // Transitions
case Joysticks_Init:
joysticks_state = Joysticks_Get_Turn;
break;
case Joysticks_Get_Turn:
joysticks_state = Joysticks_Get_Throttle;
break;
case Joysticks_Get_Throttle:
joysticks_state = Joysticks_Get_Turn;
break;
default:
joysticks_state = Joysticks_Init;
break;
}
switch(joysticks_state){ // Actions
case Joysticks_Init:
ADC_init();
for(unsigned i = 0; i < 25; ++i){asm("nop");}
bt_data = 0x00;
break;
case Joysticks_Get_Turn:
ADMUX = 0x00;
for(unsigned i = 0; i < 15; ++i){asm("nop");}
turn_input = (int)ADC;
adc_translation = Translate(turn_input);
if (adc_translation == 1){
bt_data = (bt_data & 0xFC) | 0x01;
}
else if (adc_translation == 2){
bt_data = (bt_data & 0xFC) | 0x02;
}
else {
bt_data = (bt_data & 0xFC) | 0x03;
}
break;
case Joysticks_Get_Throttle:
ADMUX = 0x01;
for(unsigned i = 0; i < 15; ++i){asm("nop");}
throttle_input = (int)ADC;
adc_translation = Translate(throttle_input);
if (adc_translation == 1){
bt_data = (bt_data & 0xCF) | 0x10;
}
else if (adc_translation == 2){
bt_data = (bt_data & 0xCF) | 0x20;
}
else {
bt_data = (bt_data & 0xCF) | 0x30;
}
break;
default:
break;
}
}
void Button_Tick(){
unsigned char button_press = ~PINC & 0x01;
switch(button_state){ // Transitions
case Press1:
if (button_press){
button_state = Wait1;
}
else {
button_state = Press1;
}
break;
case Wait1:
if (button_press){
button_state = Wait1;
}
else {
button_state = Press2;
}
break;
case Press2:
if (button_press){
button_state = Wait2;
}
else {
button_state = Press2;
}
break;
case Wait2:
if (button_press){
button_state = Wait2;
}
else {
button_state = Press1;
}
break;
default:
button_state = Wait2;
break;
} // Transitions
switch(button_state){ // Actions
case Press1:
break;
case Wait1:
PORTB = 0x01;
is_automatic = 1;
break;
case Press2:
break;
case Wait2:
PORTB = 0x00;
is_automatic = 0;
break;
default:
break;
} // Actions
}
#endif /* CONTROLLER_H_ */<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Servant Module
* Motor Drivers
*
* Using Atmega1284
*/
#ifndef MOTOR_DRIVER_H_
#define MOTOR_DRIVER_H_
#include "bit.h"
// Bluetooth data
extern unsigned char bt_data;
extern unsigned char manual_movement;
// Automatic
enum Auto_D_Signal {AUTO_STOP, AUTO_FORWARD, AUTO_BACKWARD, AUTO_LEFT, AUTO_RIGHT} auto_drive_signal;
// Manual
#define FORWARD_LEFT 0x31
#define FORWARD 0x32
#define FORWARD_RIGHT 0x33
#define BACKWARD_LEFT 0x11
#define BACKWARD 0x12
#define BACKWARD_RIGHT 0x13
// MTD-01 Motor Driver Port
#define MDA_PORT PORTA
#define MDB_PORT PORTA
// DRV8833 Motor Driver Port
#define MDC_PORT PORTB
#define MDD_PORT PORTB
// MTD-01 Pin-out for DC Motor 1
#define MDA_en 0 // PA0
#define MDA_in1 1 // PA1
#define MDA_in2 2 // PA2
// MTD-01 Pin-out for DC Motor 2
#define MDB_en 3 // PA3
#define MDB_in1 4 // PA4 (in3)
#define MDB_in2 5 // PA5 (in4)
// DRV8833 Pin-out for Enable Signal
#define MDcd_en 0 // PB0 (Slp)
// DRV8833 Pin-out for DC Motor 3
#define MDC_in1 1 // PB1 (Ain1)
#define MDC_in2 2 // PB2 (Ain2)
// DRV8833 Pin-out for DC Motor 4
#define MDD_in1 3 // PB3 (Bin1)
#define MDD_in2 4 // PB4 (Bin2)
enum Manual_Drive_SM {D_Stop, D_Forward_Left, D_Forward, D_Forward_Right, D_Backward_Left, D_Backward, D_Backward_Right} manual_drive_state;
enum Auto_Drive_SM {Auto_D_Stop, Auto_D_Forward, Auto_D_Backward, Auto_D_Left, Auto_D_Right} auto_drive_state;
void Manual_Drive_Tick(){
manual_movement = bt_data & 0x7F;
switch (manual_movement){ // Optimized Transitions
case FORWARD_LEFT:
manual_drive_state = D_Forward_Left;
break;
case FORWARD:
manual_drive_state = D_Forward;
break;
case FORWARD_RIGHT:
manual_drive_state = D_Forward_Right;
break;
case BACKWARD_LEFT:
manual_drive_state = D_Backward_Left;
break;
case BACKWARD:
manual_drive_state = D_Backward;
break;
case BACKWARD_RIGHT:
manual_drive_state = D_Backward_Right;
break;
default:
manual_drive_state = D_Stop;
break;
} // Optimized Transitions
switch (manual_drive_state){ // Actions
case D_Stop: // No movement
MDA_PORT = SetBit(MDA_PORT, MDA_en, 0); // ---Motor A---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 0); // ---Motor B---
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 0); // ---Motor C and D ---
break;
case D_Forward_Left:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 1);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
case D_Forward:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 1);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 1);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
case D_Forward_Right:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 1);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
case D_Backward_Left:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 0);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 1);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 1);
break;
case D_Backward:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 0);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 1);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 0);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 1);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 1);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 1);
break;
case D_Backward_Right:
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 0);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 1);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 1);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
default:
break;
} // Actions
}
void Auto_Drive_Tick(){
switch (auto_drive_signal){ // Optimized Transitions
case AUTO_FORWARD:
auto_drive_state = Auto_D_Forward;
break;
case AUTO_BACKWARD:
auto_drive_state = Auto_D_Backward;
break;
case AUTO_LEFT:
auto_drive_state = Auto_D_Left;
break;
case AUTO_RIGHT:
auto_drive_state = Auto_D_Right;
break;
default:
auto_drive_state = Auto_D_Stop;
break;
} // Optimized Transitions
switch(auto_drive_state){ // Actions
case Auto_D_Stop: // Turn off all motors
MDA_PORT = SetBit(MDA_PORT, MDA_en, 0); // ---Motor A---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 0); // ---Motor B---
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 0); // ---Motor C and D ---
break;
case Auto_D_Forward: // Power all 4 motors
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 1);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 1);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
case Auto_D_Backward: // Power all 4 motors in REVERSE
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 0);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 1);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 0);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 1);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 1);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 1);
break;
case Auto_D_Left: // Power ONLY rightmost motors forward
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in1, 1);
MDB_PORT = SetBit(MDB_PORT, MDB_in2, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 0);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 1);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
case Auto_D_Right: // Power ONLY leftmost motors
// ---Motor A---
MDA_PORT = SetBit(MDA_PORT, MDA_en, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in1, 1);
MDA_PORT = SetBit(MDA_PORT, MDA_in2, 0);
// ---Motor B---
MDB_PORT = SetBit(MDB_PORT, MDB_en, 0);
// Enables Motors C and D
MDC_PORT = SetBit(MDC_PORT, MDcd_en, 1);
// ---Motor C---
MDC_PORT = SetBit(MDC_PORT, MDC_in1, 1);
MDC_PORT = SetBit(MDC_PORT, MDC_in2, 0);
// ---Motor D---
MDD_PORT = SetBit(MDD_PORT, MDD_in1, 0);
MDD_PORT = SetBit(MDD_PORT, MDD_in2, 0);
break;
default:
break;
} // Actions
}
void Manual_Drive_Tick_Task(){
manual_drive_state = -1;
while(1)
{
if ((bt_data & 0x80) == 0){
Manual_Drive_Tick();
}
vTaskDelay(500);
}
}
void Auto_Drive_Tick_Task()
{
auto_drive_state = -1;
while(1)
{
if ((bt_data & 0x80) != 0){
Auto_Drive_Tick();
}
vTaskDelay(500);
}
}
#endif<file_sep>////////////////////////////////////////////////////////////////////////////////
// Permission to copy is granted provided that this header remains intact.
// This software is provided with no warranties.
////////////////////////////////////////////////////////////////////////////////
#ifndef __ADC_H__
#define __ADC_H__
void ADC_init() {
ADCSRA |= (1 << ADEN) | (1 << ADSC) | (1 << ADATE);
}
#endif<file_sep># Autonomous-RC-Car
Embedded systems project.
## Getting Started
These instructions will help you to build your own RC Car.
#### Hardware Requirements
- 2 Atmega1284 microcontrollers
- Acrobatics Junior Runt Rover (comes with 4 DC motors)
- MTD-01 motor driver
- DRV8833 motor driver
- HC-SR05 ultrasonic sensor
- 2 HC-05 bluetooth modules
#### Software Requirements
- Atmel Studio 7.0
## Walkthrough
In progress
#### Acknowledgements
- UCR
- <NAME>
<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Servant Module
* Bluetooth
*
* Using Atmega1284
*/
#ifndef BLUETOOTH_SLAVE_H_
#define BLUETOOTH_SLAVE_H_
#include "bit.h"
//#include "usart.h"
void initUSART(unsigned char usartNum)
{
if (usartNum != 1) {
UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01);
UBRR0L = BAUD_PRESCALE;
UBRR0H = (BAUD_PRESCALE >> 8);
}
else {
UCSR1B |= (1 << RXEN1) | (1 << TXEN1);
UCSR1C |= (1 << UCSZ10) | (1 << UCSZ11);
UBRR1L = BAUD_PRESCALE;
UBRR1H = (BAUD_PRESCALE >> 8);
}
}
unsigned char USART_HasReceived(unsigned char usartNum)
{
return (usartNum != 1) ? (UCSR0A & (1 << RXC0)) : (UCSR1A & (1 << RXC1));
}
unsigned char bt_data = 0x00;
unsigned char manual_movement = 0x00;
enum BT_Slave_SM {BT_Slave_Init, BT_Slave_Check_Ready, BT_Slave_Receive} bt_slave_state;
void BT_Slave_Tick(){
switch (bt_slave_state){ // Transitions
case BT_Slave_Init:
bt_slave_state = BT_Slave_Check_Ready;
break;
case BT_Slave_Check_Ready:
if (USART_HasReceived(0)){
bt_slave_state = BT_Slave_Receive;
}
else{
bt_slave_state = BT_Slave_Check_Ready;
}
break;
case BT_Slave_Receive:
bt_slave_state = BT_Slave_Check_Ready;
break;
default:
bt_slave_state = BT_Slave_Init;
break;
}
switch (bt_slave_state){ // Actions
case BT_Slave_Init:
initUSART(0);
break;
case BT_Slave_Check_Ready:
break;
case BT_Slave_Receive:
bt_data = UDR0;
break;
}
}
void BT_Slave_Tick_Task()
{
bt_slave_state = -1;
while(1)
{
BT_Slave_Tick();
vTaskDelay(1);
}
}
#endif /* BLUETOOTH_SLAVE_H_ */<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Master Module
*
* Using Atmega1284
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "adc.h"
#include "controller.h"
#include "bluetooth_master.h"
#include "timer.h"
// Master Module Pin-out
// * Rx = PD0
// * Tx = PD1
int main(void)
{
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00; // Arduino testing as well; just remove led wire
DDRC = 0x00; PORTC = 0xFF;
bt_data = 0x00;
bt_slave_state = -1;
joysticks_state = -1;
button_state = -1;
TimerSet(10);
TimerOn();
unsigned char counter = 0x00;
while (1)
{
BT_Master_Tick();
Joysticks_Tick();
if (counter >= 10){
Button_Tick();
}
else{
counter++;
}
while(!TimerFlag){}
TimerFlag = 0;
}
}
<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Master Module
* Bluetooth
*
* Using Atmega1284
*/
#ifndef BLUETOOTH_MASTER_H_
#define BLUETOOTH_MASTER_H_
// USART Setup Values
#define F_CPU 8000000UL // Assume uC operates at 8MHz
#define BAUD_RATE 38400
#define BAUD_PRESCALE (((F_CPU / (BAUD_RATE * 16UL))) - 1)
unsigned char bt_data = 0x00;
extern unsigned char is_automatic;
enum BT_Master_SM {BT_Master_Init, BT_Master_Check_Ready, BT_Master_Send} bt_slave_state;
void initUSART(unsigned char usartNum)
{
if (usartNum != 1) {
UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01);
UBRR0L = BAUD_PRESCALE;
UBRR0H = (BAUD_PRESCALE >> 8);
}
else {
UCSR1B |= (1 << RXEN1) | (1 << TXEN1);
UCSR1C |= (1 << UCSZ10) | (1 << UCSZ11);
UBRR1L = BAUD_PRESCALE;
UBRR1H = (BAUD_PRESCALE >> 8);
}
}
unsigned char USART_IsSendReady(unsigned char usartNum)
{
return (usartNum != 1) ? (UCSR0A & (1 << UDRE0)) : (UCSR1A & (1 << UDRE1));
}
unsigned char USART_HasTransmitted(unsigned char usartNum)
{
return (usartNum != 1) ? (UCSR0A & (1 << TXC0)) : (UCSR1A & (1 << TXC1));
}
unsigned char USART_HasReceived(unsigned char usartNum)
{
return (usartNum != 1) ? (UCSR0A & (1 << RXC0)) : (UCSR1A & (1 << RXC1));
}
void USART_Flush(unsigned char usartNum)
{
static unsigned char dummy;
if (usartNum != 1) {
while ( UCSR0A & (1 << RXC0) ) { dummy = UDR0; }
}
else {
while ( UCSR1A & (1 << RXC1) ) { dummy = UDR1; }
}
}
void USART_Send(unsigned char sendMe, unsigned char usartNum)
{
if (usartNum != 1) {
while( !(UCSR0A & (1 << UDRE0)) );
UDR0 = sendMe;
}
else {
while( !(UCSR1A & (1 << UDRE1)) );
UDR1 = sendMe;
}
}
unsigned char USART_Receive(unsigned char usartNum)
{
if (usartNum != 1) {
while ( !(UCSR0A & (1 << RXC0)) ); // Wait for data to be received
return UDR0; // Get and return received data from buffer
}
else {
while ( !(UCSR1A & (1 << RXC1)) );
return UDR1;
}
}
void BT_Master_Tick(){
switch (bt_slave_state){ // Transitions
case BT_Master_Init:
bt_slave_state = BT_Master_Check_Ready;
break;
case BT_Master_Check_Ready:
if (USART_IsSendReady(0)){
bt_slave_state = BT_Master_Send;
}
else{
bt_slave_state = BT_Master_Check_Ready;
}
break;
case BT_Master_Send:
bt_slave_state = BT_Master_Check_Ready;
break;
default:
bt_slave_state = BT_Master_Init;
break;
}
switch (bt_slave_state){ // Actions
case BT_Master_Init:
initUSART(0);
break;
case BT_Master_Check_Ready:
break;
case BT_Master_Send:
if (is_automatic){
bt_data = 0x80;
}
else {
bt_data &= 0x7F;
}
USART_Send(bt_data, 0);
break;
}
}
#endif /* BLUETOOTH_MASTER_H_ */<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car
* Servant Module
*
* Using Atmega1284
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <avr/portpins.h>
#include <avr/pgmspace.h>
// USART Setup Values
#define F_CPU 8000000UL // Assume uC operates at 8MHz
#define BAUD_RATE 38400
#define BAUD_PRESCALE (((F_CPU / (BAUD_RATE * 16UL))) - 1)
#include <util/delay.h>
//FreeRTOS include files
#include "FreeRTOS.h"
#include "task.h"
#include "croutine.h"
//Other include files
#include "bluetooth_slave.h"
#include "motor_driver.h"
#include "ultrasonic_sensor.h"
void CreateTasks(unsigned portBASE_TYPE Priority_BT, unsigned portBASE_TYPE Priority_USS, unsigned portBASE_TYPE Priority_Auto, unsigned portBASE_TYPE Priority_Man )
{
xTaskCreate(BT_Slave_Tick_Task, (signed portCHAR *)"BT_Slave_Tick_Task", configMINIMAL_STACK_SIZE, NULL, Priority_BT, NULL);
xTaskCreate(USS_Tick_Task, (signed portCHAR *)"USS_Tick_Task", configMINIMAL_STACK_SIZE, NULL, Priority_USS, NULL);
xTaskCreate(Auto_Drive_Tick_Task, (signed portCHAR *)"Auto_Drive_Tick_Task", configMINIMAL_STACK_SIZE, NULL, Priority_Auto, NULL);
xTaskCreate(Manual_Drive_Tick_Task, (signed portCHAR *)"Manual_Drive_Tick_Task", configMINIMAL_STACK_SIZE, NULL, Priority_Man, NULL);
}
int main(void)
{
DDRA = 0xFF; PORTA = 0x00; // MTD-01
DDRB = 0xFF; PORTB = 0x00; // DRV8333 + USS Trig
DDRC = 0x00; PORTC = 0xFF; // USS Echo
// DDRD = ; PORTD = ; // Bluetooth Module
CreateTasks(2, 1, 1, 1);
vTaskStartScheduler();
return 0;
}
<file_sep>/*
* <NAME>
* <EMAIL>
* UCR - CS 122A
*
* RC Car Project
* Servant Module
* Ultrasonic Sensor
*
* Using Atmega1284
*/
#ifndef ULTRASONIC_SENSOR_H_
#define ULTRASONIC_SENSOR_H_
#define USS_TRIG_PORT PORTB
#define USS_ECHO_PORT PINC
#define TRIG_PIN 5 // Trig is PB5 => OUTPUT
#define ECHO_PIN 0x01 // Echo is PC0 => INPUT
const unsigned long USS_TIMEOUT = 3000; // 3 second timeout
unsigned long duration = 0; // Pulse duration in ms
unsigned int distance = 0; // Object distance in cm
enum USS_SM {USS_TriggerPulse, USS_WaitForHigh, USS_WaitForLow} USS_state;
unsigned int millisecondsToCentimeters(unsigned long milliseconds){ // For USS distance calculation
return (unsigned int)(milliseconds / 2.0 / 29.0 * 1000 );
}
void USS_Tick(){
switch (USS_state){ // Transitions
case USS_TriggerPulse:
USS_state = USS_WaitForHigh;
break;
case USS_WaitForHigh:
if ( (USS_ECHO_PORT & ECHO_PIN) != 0){
// Echo Pin is High
duration = 0;
USS_state = USS_WaitForLow;
}
else {
//Retry pulse
USS_state = USS_TriggerPulse;
}
break;
case USS_WaitForLow:
if ( (USS_ECHO_PORT & ECHO_PIN) != 0 && duration < USS_TIMEOUT){
// Echo Pin is high and the pulse hasn't timed out
USS_state = USS_WaitForLow;
}
else {
if (duration >= USS_TIMEOUT){ // Timed out
auto_drive_signal = AUTO_FORWARD;
}
else{ // Calculate distance and display on LED
distance = millisecondsToCentimeters(duration);
if (distance > 100){
auto_drive_signal = AUTO_FORWARD;
}
else if (distance > 50){
auto_drive_signal = AUTO_RIGHT;
}
else{
auto_drive_signal = AUTO_BACKWARD;
}
}
duration = 0;
USS_state = USS_TriggerPulse;
}
break;
default:
USS_state = USS_TriggerPulse;
auto_drive_signal = AUTO_STOP;
break;
} // Transitions
switch (USS_state){ // Actions
case USS_TriggerPulse:
USS_TRIG_PORT = SetBit(USS_TRIG_PORT, TRIG_PIN, 1);
_delay_us(10);
USS_TRIG_PORT = SetBit(USS_TRIG_PORT, TRIG_PIN, 0);
break;
case USS_WaitForHigh:
break;
case USS_WaitForLow:
++duration;
break;
default:
break;
} // Actions
}
void USS_Tick_Task()
{
USS_state = -1;
while(1)
{
if ((bt_data & 0x80) != 0){
USS_Tick();
}
vTaskDelay(1);
}
}
#endif /* ULTRASONIC_SENSOR_H_ */ | eb21085d544423d079de4ba666b2e39d058eb124 | [
"Markdown",
"C"
] | 9 | C | jrile002/Autonomous-RC-Car | bbe1fccb07417cf0116b536a8bd2b9d7cb65c408 | d1bc5c64a780cd869e6bf8744f9d91042b36e21c |
refs/heads/main | <repo_name>CH1STY/Learning-reactjs-spring-2020-2021-sec-b<file_sep>/FINAL_LAB_TASK/src/components/NavBar.js
import {Link,useHistory} from 'react-router-dom';
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content';
export const NavBar =()=>{
let history = useHistory();
const MySwal = withReactContent(Swal);
const logout = () =>{
MySwal.fire({
title: 'Confirm Logging Out?',
icon: 'warning',
showCancelButton: true,
}).then(result =>{
if(result.isConfirmed){
localStorage.clear();
history.push('/');
}
});
}
if(localStorage.getItem('userId')===null)
{
history.push('/');
}
return (
<div className="navBar">
<Link to='/diary'> <button className="navButton">Home </button> </Link>
<Link to='/diary/add'><button className="navButton">Add Entry To Diary </button></Link>
<Link to='/diary/viewAll'><button className="navButton">View From Diary </button></Link>
<button onClick={logout} className="btn btn-dark">Logout </button>
</div>
);
}<file_sep>/FINAL_LAB_TASK/src/components/AddToDiary.js
import {useState} from 'react';
import axios from 'axios';
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content';
export const AddToDiary=()=>{
const [detailsError,setDetailsError] = useState();
const [priorityError,setPriorityError] = useState();
const MySwal = withReactContent(Swal);
const [userInput,setInput] = useState({
details:'',
priority:'0',
userId:localStorage.getItem('userId'),
});
const FormSubmit = (e) => {
e.preventDefault();
var url = "http://localhost/reactTask2ndTry/public/api/addToDiary";
const fetchData = async () =>{
const res = await axios.post(url,userInput);
if(res.data.toString()==="okay")
{
setDetailsError("");
setPriorityError("");
setInput({
details:'',
priority:'0',
userId:localStorage.getItem('userId'),
});
MySwal.fire({
title: 'Entry Added Successfully',
icon: 'success',
showCancelButton: false,
});
}
else
{
setDetailsError (res.data.detailsError);
setPriorityError(res.data.priorityError);
}
}
fetchData();
}
const changeUser = (e)=>{
const attar = e.target.name;
const value = e.target.value;
const user = {...userInput, [attar] : value};
setInput(user);
}
return (
<div align="center">
<h1>Adding to Diary</h1>
<form onSubmit={FormSubmit}>
<table id="customers">
<tbody>
<tr>
<td>DIARY ENTRY</td>
<td>
<div className="form-group">
<input name="details" value={userInput.details} onChange={changeUser} className="form-control"></input>
</div>
{detailsError==='true' && <p className="ErrorMsg">Invalid Entry</p>}
</td>
</tr>
<tr>
<td>PRIORITY</td>
<td>
<div className="form-group">
<select className="form-select" onChange={changeUser} value={userInput.priority} name="priority" id="">
<option value="0" >Select a Priority</option>
<option value="1" >High</option>
<option value="2" >Medium</option>
<option value="3" >Low</option>
</select>
</div>
{priorityError==='true' && <p className="ErrorMsg">Invalid Priority</p>}
</td>
</tr>
<tr>
<td colSpan='2'><button className="btn btn-primary">ADD</button></td>
</tr>
</tbody>
</table>
</form>
</div>
)
}<file_sep>/FINAL_LAB_TASK/src/components/fetchData.js
import {useState, useEffect} from 'react';
import axios from 'axios';
export const useFetch = (url)=>{
const [status, setStatus] = useState(true);
const [users, setUsers] = useState([]);
const [lurl] = useState(url);
useEffect(()=>{
const fetchData = async () =>{
const res = await axios.get(lurl);
setUsers(res.data);
setStatus(false);
}
fetchData();
},[]);
return { status, users };
}<file_sep>/FINAL_LAB_TASK/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import {NavBar} from './components/NavBar';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import {AddToDiary} from './components/AddToDiary';
import {ViewAll} from './components/ViewFromDiary';
import {Login} from './components/Login';
import {EditEntry} from './components/EditEntry';
import {Home} from './components/Home';
import './index.css';
const DigitalDiary=()=>{
/*<Route exact path='/logout'>
<Logout></Logout>
</Route>*/
return(
<Router>
<Switch>
<Route exact path='/'>
<Login></Login>
</Route>
<Route path='/diary'>
<NavBar/>
<Route exact path="/diary">
<Home></Home>
</Route>
<Route path='/diary/add'>
<AddToDiary/>
</Route>
<Route exact path='/diary/viewAll'>
<ViewAll/>
</Route>
<Route path='/diary/edit/:id'>
<EditEntry></EditEntry>
</Route>
</Route>
</Switch>
</Router>
)
}
ReactDOM.render(
<DigitalDiary/>
,
document.getElementById('root')
);
<file_sep>/README.md
# Learning-reactjs-spring-2020-2021-sec-b<file_sep>/FINAL_LAB_TASK/src/components/Login.js
import {useState} from 'react';
import {useHistory} from 'react-router-dom';
import './CSS/login.css';
import axios from 'axios';
import Swal from 'sweetalert2'
import withReactContent from 'sweetalert2-react-content';
export const Login = ()=>{
const MySwal = withReactContent(Swal);
let history = useHistory();
if(localStorage.getItem('userId')!==null)
{
history.push('/diary');
}
const [errorMsg,setError] = useState();
const [userInput,setInput] = useState({
username:'',
password:'',
});
const FormSubmit = (e) => {
e.preventDefault();
var url = "http://localhost/reactTask2ndTry/public/api/login";
const fetchData = async () =>{
const res = await axios.post(url,userInput);
if(res.data[0]==='false')
{
setError('false');
}
else
{
setError('');
console.log(res.data.username);
localStorage.setItem('userId',res.data.id);
localStorage.setItem('username',res.data.username);
MySwal.fire({
title: 'Logged In Successfully',
icon: 'success',
showCancelButton: false,
}).then(result =>{
if(result.isConfirmed){
history.push('/diary');
}
});
}
}
fetchData();
}
const changeUser = (e)=>{
const attar = e.target.name;
const value = e.target.value;
const user = {...userInput, [attar] : value};
setInput(user);
}
return (
<div>
<section className="myform-area">
<div className="container">
<div className="row justify-content-center">
<div className="col-lg-8">
<div className="form-area login-form">
<div className="form-content">
<h2>Login</h2>
<p>Welcome To Digital Diary Please Login To Continue</p>
</div>
<div className="form-input">
<h2>DIGITAL DIARY</h2>
<form onSubmit={FormSubmit}>
<div className="form-group">
<input type="text" name="username" value={userInput.username} onChange={changeUser} required/>
<label>User Name</label>
</div>
<div className="form-group">
<input type="<PASSWORD>" name="password" value={userInput.password} onChange={changeUser} required/>
<label>password</label>
</div>
<div className="myform-button">
<button className="myform-btn">Login</button>
</div>
{
errorMsg === 'false' &&
<p align="center" className="ErrorMsg" >Invalid Credentials</p>
}
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
} | 64d8b788f2603245cc375c95557321e11cdb1bef | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | CH1STY/Learning-reactjs-spring-2020-2021-sec-b | 185773f88b14efb85e255bcd66455179882132c5 | 627102758584255a3795c5d987a3d7a11dd4b333 |
refs/heads/master | <repo_name>s-anusha/automatetheboringstuff<file_sep>/Chapter 8/extendingTheMulticlipboard.py
#! python3
# extendingTheMulticlipboard.py
'''
Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords.
'''
# Usage: python extendingTheMulticlipboard.py save keyword - Saves clipboard to keyword.
# python extendingTheMulticlipboard.py keyword - Loads keyword to clipboard.
# python extendingTheMulticlipboard.py list - Loads keyword list to clipboard.
# python extendingTheMulticlipboard.py delete keyword - Deletes keyword from shelf.
# python extendingTheMulticlipboard.py delete - Deletes all keywords.
import shelve, pyperclip, sys
mcbShelf = shelve.open('mcb')
if len(sys.argv) == 3:
if sys.argv[1].lower() == 'save':
mcbShelf[sys.argv[2]] = pyperclip.paste()
print('Saved to shelf from clipboard as ' + sys.argv[2])
elif sys.argv[1].lower() == 'delete' and sys.argv[2] in mcbShelf:
del mcbShelf[sys.argv[2]]
print(sys.argv[2] + ' deleted from shelf.')
elif len(sys.argv) == 2:
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbShelf.keys())))
print('Shelf keyword list copied to clipboard.')
elif sys.argv[1].lower() == 'delete':
for key in mcbShelf:
del mcbShelf[key]
print('All keywords deleted from shelf.')
elif sys.argv[1] in mcbShelf:
pyperclip.copy(mcbShelf[sys.argv[1]])
print(sys.argv[1] + ' value copied from shelf to clipboard.')
else:
print('Invalid.')
else:
print('''\nUsage:
python extendingTheMulticlipboard.py save keyword - Saves clipboard to keyword.
python extendingTheMulticlipboard.py keyword - Loads keyword to clipboard.
python extendingTheMulticlipboard.py list - Loads keyword list to clipboard.
python extendingTheMulticlipboard.py delete keyword - Deletes keyword from shelf.
python extendingTheMulticlipboard.py delete - Deletes all keywords.''')
mcbShelf.close()
<file_sep>/Chapter 11/imageSiteDownloader.py
#! python3
# imageSiteDownloader.py - untested
'''
Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then downloads all the resulting images. You could write a program that works with any photo site that has a search feature.
'''
# Usage: python imageSiteDownloader.py site_url search_category
from selenium import webdriver
import sys
if len(sys.argv) < 3:
print('Usage: python imageSiteDownloader.py site_url search_category")
sys.exit()
#siteUrl = sys.argv[1]
siteUrl = 'https://www.flickr.com/'
searchCategory = sys.argv[2]
print('Opening Firefox...')
browser = webdriver.Firefox()
print('Opening ' + siteUrl + '...')
browser.get(siteUrl)
print('Searching for ' + searchCategory + '...')
searchElement = browser.find_element_by_link_id('search-field')
searchElement.send_keys(searchCategory)
searchElement.send_keys(Keys.ENTER)
# print('Filtering by creative commons license...')
# licenseElement = browser.find_element_by_class('filter-license')
# licenseELement.click()
# click All creative commons
print('Downloading images...')
imageElements = browser.find_elements_by_partial_link_text('/photos/')
for i in range(imageElements):
imageElements[i].click()
downloadElement = browser.find_element_by_class('download')
downloadElement.click()
sizeElement = browser.find_element_by_link_text('View all sizes')
sizeElement.click()
try:
originalElement = browser.find_element_by_link_text('Original')
originalElement.click()
downloadLinkElement = browser.find_element_by_link_text('Download the Original size of this photo')
downloadlinkElement.click()
except NoSuchElement:
continue
print('Closing Firefox...')
browser.quit()
print('Done')
<file_sep>/Chapter 8/regexSearch.py
#! python3
# regexSearch.py
'''
Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen.
'''
# Usage: python regexSearch.py
import os, re
print('Enter regular expression: ')
userRegex = input()
searchRegex = re.compile(userRegex)
print('\n')
for file in os.listdir('.'):
if file.endswith('.txt'):
print(file)
checkFile = open(file, 'r')
for line in checkFile:
found = searchRegex.findall(line)
print(found)
checkFile.close()
print('\n')
<file_sep>/Chapter 16/randomChoreAssignmentEmailer.py
#! python3
# randomChoreAssignmentEmailer.py - untested
'''
Write a program that takes a list of people’s email addresses and a list of chores that need to be done and randomly assigns chores to people. Email each person their assigned chores. If you’re feeling ambitious, keep a record of each person’s previously assigned chores so that you can make sure the program avoids assigning anyone the same chore they did last time. For another possible feature, schedule the program to run once a week automatically.
Here’s a hint: If you pass a list to the random.choice() function, it will return a randomly selected item from the list. Part of your code could look like this:
chores = ['dishes', 'bathroom', 'vacuum', 'walk dog']
randomChore = random.choice(chores)
chores.remove(randomChore) # this chore is now taken, so remove it
'''
# Usage: python randomChoreAssignmentEmailer.py
import random
import smtplib
emails = ['<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>']
chores = ['dishes', 'bathroom', 'vacuum', 'walk dog']
print('Logging in...')
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(' <EMAIL> ', ' MY_SECRET_PASSWORD ')
print('Sending e-mails...')
for email in emails:
randomChore = random.choice(chores)
chores.remove(randomChore) # this chore is now taken, so remove it
sendmailStatus = smtpObj.sendmail(' <EMAIL> ', email,
'Subject: Chore.\nHello, \nYour chore for the week is: %s. Sincerely, Bob' % randomChore)
print('Sending email to %s...' % email)
if sendmailStatus != {}:
print('There was a problem sending email to %s: %s' % (email, sendmailStatus))
print('Logging out...')
smtpObj.quit()
print('Done.')
<file_sep>/Chapter 15/scheduledWebComicDownloader.py
#! python3
# scheduledWebComicDownloader.py
'''
Write a program that checks the websites of several web comics and automatically downloads the images if the comic was updated since the program’s last visit. Your operating system’s scheduler (Scheduled Tasks on Windows, launchd on OS X, and cron on Linux) can run your Python program once a day. The Python program itself can download the comic and then copy it to your desktop so that it is easy to find. This will free you from having to check the website yourself to see whether it has updated. (A list of web comics is available at http://nostarch.com/automatestuff/.)
'''
# Usage: python scheduledWebComicDownloader.py
import requests, os, bs4
urlDict = {'http://www.lefthandedtoons.com/': 'Left-handed Toons',
'http://www.savagechickens.com/': 'Savage Chickens',
'http://www.lunarbaboon.com': 'Lunar Baboon',
'http://completelyseriouscomics.com/': 'Completely Serious Comics',
'http://www.exocomics.com/': 'Extra Ordinary',
'http://nonadventures.com/': 'Wonderella',
'http://www.happletea.com/': 'Happle Tea'}
linkSelector = {'http://www.lefthandedtoons.com/': '.comicimage',
'http://www.savagechickens.com/': '.entry_content p img',
'http://www.lunarbaboon.com': '.full-image-block img',
'http://completelyseriouscomics.com/': '#comic-1 img',
'http://www.exocomics.com/': '.comic img',
'http://nonadventures.com/': '#comic img',
'http://www.happletea.com/': '#comic img'}
def getSelector(link):
return linkSelector.get(link, None)
def getComicUrl(link, comicElem):
if link == 'http://www.lunarbaboon.com':
comicUrl = link + comicElem[0].get('src')
baseName = os.path.basename(comicUrl).split('?__')[0]
return comicUrl, baseName
else:
comicUrl = comicElem[0].get('src')
baseName = os.path.basename(comicUrl)
return comicUrl, baseName
for site in urlDict.values():
os.makedirs(site, exist_ok=True) # store comics in ./url
for link in urlDict.keys():
if not link.endswith('#'):
# Download the page.
print('Downloading page %s...' % link)
res = requests.get(link)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, features="html.parser")
# Find the URL of the comic image.
# comicElem = soup.select('#comic img')
comicElem = soup.select(getSelector(link))
if comicElem == []:
print('Could not find comic image.')
else:
try:
comicUrl, baseName = getComicUrl(link, comicElem)
if comicUrl is None or baseName is None:
continue
if os.path.isfile(os.path.join(urlDict[link], baseName)):
# If image already, exists, do nothing
print('Image %s already exists.' % (comicUrl))
continue
else:
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./link.
imageFile = open(os.path.join(urlDict[link], baseName), 'wb')
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
except requests.exceptions.MissingSchema:
# skip this comic
continue
print('Done.')
<file_sep>/Chapter 13/pdfParanoia.py
#! python 3
# pdfParanoia.py
'''
Using the os.walk() function from Chapter 9, write a script that will go through every PDF in a folder (and its subfolders) and encrypt the PDFs using a password provided on the command line. Save each encrypted PDF with an _encrypted.pdf suffix added to the original filename. Before deleting the original file, have the program attempt to read and decrypt the file to ensure that it was encrypted correctly.
Then, write a program that finds all encrypted PDFs in a folder (and its subfolders) and creates a decrypted copy of the PDF using a provided password. If the password is incorrect, the program should print a message to the user and continue to the next PDF.
'''
# Usage: python pdfParanoia.py folder_path
import os
import PyPDF2
import sys
if len(sys.argv) < 2:
print("Usage: python pdfParanoia.py folder_path")
sys.exit()
folder = sys.argv[1]
print('Part 1: Encryption\n')
for folderName, subfolders, filenames in os.walk(folder):
for filename in filenames:
if filename.endswith('.pdf'):
pdfFile = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
print('Enter password for ' + filename + ': ')
password = input()
print('Encrypting file...')
pdfWriter.encrypt(password)
newFilename = filename[:len(filename) - 4] + '_encrypted.pdf'
resultPdf = open(newFilename, 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
pdfFile.close()
print('Testing encryption...')
checkPdfReader = PyPDF2.PdfFileReader(open(newFilename, 'rb'))
if checkPdfReader.isEncrypted is False:
print('Encryption of ' + filename + ' failed.')
else:
checkPdfReader.decrypt(password)
try:
pageObj = checkPdfReader.getPage(0)
print('Encryption success.\nDeleting original file...')
os.unlink(os.path.abspath(filename))
print('Done.')
except PyPDF2.utils.PdfReadError:
print('Failed to retrieve page object from encrypted ' + filename)
print('Part 1 complete.\n')
print('Part 2: Decryption\n')
for folderName, subfolders, filenames in os.walk(folder):
for filename in filenames:
if filename.endswith('_encrypted.pdf'):
pdfFile = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
if pdfReader.isEncrypted is False:
print('File not encrypted.')
else:
print('Enter password for ' + filename + ': ')
password = input()
print('Decrypting file...')
if pdfReader.decrypt(password) is 0:
print('Decryption failed.')
else:
print('Decryption success.\nCreating a copy...')
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
newFilename = filename[:len(filename) - 14] + '.pdf'
resultPdf = open(newFilename, 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
print('Done.')
pdfFile.close()
print('Part 2 complete.')
<file_sep>/Chapter 11/2048.py
#! python3
# 2048.py
'''
2048 is a simple game where you combine tiles by sliding them up, down, left, or right with the arrow keys. You can actually get a fairly high score by repeatedly sliding in an up, right, down, and left pattern over and over again. Write a program that will open the game at https://gabrielecirulli.github.io/2048/ and keep sending up, right, down, and left keystrokes to automatically play the game.
'''
# Usage: python 2048.py
from selenium import webdriver
siteUrl = 'https://gabrielecirulli.github.io/2048/'
print('Opening Firefox...')
browser = webdriver.Firefox()
print('Opening ' + siteUrl + '...')
browser.get(siteUrl)
print('Closing Firefox...')
browser.quit()
print('Done')
<file_sep>/Chapter 12/spreadsheetCellInverter.py
#! python3
# spreadsheetCellInverter.py
'''
Write a program to invert the row and column of the cells in the spreadsheet. For example, the value at row 5, column 3 will be at row 3, column 5 (and vice versa). This should be done for all cells in the spreadsheet.
You can write this program by using nested for loops to read in the spreadsheet's data into a list of lists data structure. This data structure could have sheetData[x][y] for the cell at column x and row y. Then, when writing out the new spreadsheet, use sheetData[y][x] for the cell at column x and row y.
'''
# Usage: python spreadsheetCellInverter.py fileName
import openpyxl
import sys
if len(sys.argv) < 2:
print('Usage: python spreadsheetCellInverter.py fileName')
sys.exit()
file = sys.argv[1]
wbRead = openpyxl.load_workbook(file)
readSheet = wbRead.active
wbWrite = openpyxl.Workbook()
writeSheet = wbWrite.active
for rowOfReadCellObjects in readSheet[readSheet.cell(row=1, column=1).coordinate:readSheet.cell(row=readSheet.max_row, column=readSheet.max_column).coordinate]:
for readCell in rowOfReadCellObjects:
writeSheet.cell(row=readCell.row, column=readCell.column).value = readSheet.cell(row=readCell.column, column=readCell.row).value
wbWrite.save('spreadsheetCellInverted.xlsx')
<file_sep>/Chapter 17/customSeatingCards.py
#! python3
# customSeatingCards.py
'''
Chapter 13 included a practice project to create custom invitations from a list of guests in a plaintext file. As an additional project, use the pillow module to create images for custom seating cards for your guests. For each of the guests listed in the guests.txt file from the resources at http://nostarch.com/automatestuff/, generate an image file with the guest name and some flowery decoration. A public domain flower image is available in the resources at http://nostarch.com/automatestuff/.
To ensure that each seating card is the same size, add a black rectangle on the edges of the invitation image so that when the image is printed out, there will be a guideline for cutting. The PNG files that Pillow produces are set to 72 pixels per inch, so a 4×5-inch card would require a 288×360-pixel image.
'''
# Usage: python customSeatingCards.py
import os
from PIL import Image, ImageDraw
file = open('guests.txt', 'r')
guestList = []
for line in file:
guestList.append(line.strip())
SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'flower.jpg'
logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size
os.makedirs('invitations', exist_ok=True)
for guest in guestList:
im = Image.new('RGBA', (288, 360), 'white')
width, height = im.size
draw = ImageDraw.Draw(im)
textWidth, textHeight = draw.textsize(guest)
if (width - logoWidth < textWidth or height - logoHeight < textHeight):
continue
im.paste(logoIm, (width - logoWidth - 1, height - logoHeight - 1))
draw.text((1, 1), guest, fill='black')
draw.rectangle((0, 0, 287, 359), outline='black')
im.save(os.path.join('invitations', guest) + '.png')
<file_sep>/README.md
# Automate the Boring Stuff with Python
## Practice Projects
#### Chapter 3 – Functions
- [] theCollatzSequence.py
#### Chapter 4 – Lists
- [] commaCode.py
- [] characterPictureGrid.py
#### Chapter 5 – Dictionaries and Structuring Data
- [] fantasyGameInventory.py
#### Chapter 6 – Manipulating Strings
- tablePrinter.py
#### Chapter 7 – Pattern Matching with Regular Expressions
- strongPasswordDetection.py
- regexVersionOfStrip.py
#### Chapter 8 – Reading and Writing Files
- extendingTheMulticlipboard.py
- madLibs.py
- regexSearch.py
#### Chapter 9 – Organizing Files
- selectiveCopy.py
- deletingUnneededFiles.py
- [] fillingInTheGaps.py
#### Chapter 10 – Debugging
#### Chapter 11 – Web Scraping
- [] commandLineEmailer.py
- [] imageSiteDownloader.py
- [] 2048.py
- [] lineVerification.py
#### Chapter 12 – Working with Excel Spreadsheets
- multiplicationTableMaker.py
- blankRowInserter.py
- spreadsheetCellInverter.py
- textFilesToSpreadsheet.py
- spreadsheetToTextFiles.py
#### Chapter 13 – Working with PDF and Word Documents
- pdfParanoia.py
- customInvitationsAsWordDocuments.py
- brute-forcePdfPasswordBreaker.py
#### Chapter 14 – Working with CSV Files and JSON Data
- excel-To-CSV-Converter.py
#### Chapter 15 – Keeping Time, Scheduling Tasks, and Launching Programs
- prettifiedStopwatch.py
- scheduledWebComicDownloader.py
#### Chapter 16 – Sending Email and Text Messages
- [] randomChoreAssignmentEmailer
- [] umbrellaReminder.py
- [] autoUnsubscriber.py
- [] controllingYourComputerThroughEmail.py
#### Chapter 17 – Manipulating Images
- extendingAndFixingTheChapterProjectPrograms.py
- identifyingPhotoFoldersOnTheHardDrive.py
- customSeatingCards.py
#### Chapter 18 – Controlling the Keyboard and Mouse with GUI Automation
- lookingBusy.py
- [] instantMessengerBot.py
- [] game-PlayingBotTutorial.py
## Reference
[Automate the Boring Stuff with Python](https://automatetheboringstuff.com "Automate the Boring Stuff with Python")
<file_sep>/Chapter 9/fillingInTheGaps.py
#! python3
# fillingInTheGaps.py
'''
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.
As an added challenge, write another program that can insert gaps into numbered files so that a new file can be added.
'''
<file_sep>/Chapter 12/textFilesToSpreadsheet.py
#! python3
# textFilesToSpreadsheet.py
'''
Write a program to read in the contents of several text files (you can make the text files yourself) and insert those contents into a spreadsheet, with one line of text per row. The lines of the first text file will be in the cells of column A, the lines of the second text file will be in the cells of column B, and so on.
Use the readlines() File object method to return a list of strings, one string per line in the file. For the first file, output the first line to column 1, row 1. The second line should be written to column 1, row 2, and so on. The next file that is read with readlines() will be written to column 2, the next file to column 3, and so on.
'''
# Usage: python textFilesToSpreadsheet.py
import openpyxl
import os
wbWrite = openpyxl.Workbook()
writeSheet = wbWrite.active
rowNumber = 1
columnNumber = 1
for fileName in os.listdir(os.getcwd()):
if fileName.endswith('.txt'):
file = open(fileName, 'r')
lines = file.readlines()
for line in lines:
writeSheet.cell(row=rowNumber, column=columnNumber).value = line
rowNumber += 1
columnNumber += 1
rowNumber = 1
file.close()
wbWrite.save('textFilesToSpreadsheet.xlsx')
<file_sep>/Chapter 7/regexVersionofStrip.py
#! python3
# regexVersionOfStrip.py
'''
Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.
'''
# Usage: python regexVersionOfStrip.py string [substring_to_strip]
import re
def regexStrip(toStrip):
string = toStrip[1]
if len(toStrip) == 2:
beginningWhitespaceRegex = re.compile(r'^\s+')
string = beginningWhitespaceRegex.sub('', string)
endWhitespaceRegex = re.compile(r'\s+$')
string = endWhitespaceRegex.sub('', string)
else:
substringToRemove = toStrip[2]
beginningCharactersRegex = re.compile(r'^['+ substringToRemove +']*|['+ substringToRemove +']*$')
string = beginningCharactersRegex.sub('', string)
return string
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python regexVersionOfStrip.py string [substring_to_strip]')
sys.exit()
string = regexStrip(sys.argv)
print('String after stripping: ' + string)
<file_sep>/Chapter 9/deletingUnneededFiles.py
#! python3
# deletingUnneededFiles.py
'''
It's not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you're trying to free up room on your computer, you'll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them.
Write a program that walks through a folder tree and searches for exceptionally large files or folders-say, ones that have a file size of more than 100MB. (Remember, to get a file's size, you can use os.path.getsize() from the os module.) Print these files with their absolute path to the screen.
'''
# Usage: python deletingUnneededFiles.py sizeInBytes
import sys, os
if len(sys.argv) < 2:
print('Usage: python deletingUnneededFiles.py sizeInBytes')
sys.exit()
size = sys.argv[1]
size = int (size)
print('Enter folder path: ')
sourceFolder = raw_input()
print('\n')
print('Files to delete:')
for folderName, subfolders, filenames in os.walk(sourceFolder):
for filename in filenames:
filepath = os.path.join(folderName, filename)
fileSize = os.path.getsize(filepath)
if fileSize > size:
print(filepath)
<file_sep>/Chapter 7/strongPasswordDetection.py
#! python3
# strongPasswordDetection.py
'''
Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
'''
# Usage: Usage: python strongPasswordDetection.py password
import re
passwordLengthRegex = re.compile(r'^\S{8,}$') # password is eight characters long
passwordUppercaseRegex = re.compile(r'[A-Z]') # password contains at least one uppercase character
passwordLowercaseRegex = re.compile(r'[a-z]') # password contains at least one lowercase character
passwordDigitRegex = re.compile(r'\d') # password has at least one digit
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python strongPasswordDetection.py password')
sys.exit()
password = sys.argv[1]
lengthMatch = passwordLengthRegex.search(password)
if lengthMatch is None:
print('Password should be at least eight characters long.')
sys.exit()
uppercaseMatch = passwordUppercaseRegex.search(password)
if uppercaseMatch is None:
print('Password should contain at least one uppercase character.')
sys.exit()
lowercaseMatch = passwordLowercaseRegex.search(password)
if lowercaseMatch is None:
print('Password should contain at least one lowercase character.')
sys.exit()
digitMatch = passwordDigitRegex.search(password)
if digitMatch is None:
print('Password should have at least one digit.')
sys.exit()
print('Password accepted.')
<file_sep>/Chapter 13/brute-forcePdfPasswordBreaker.py
#! python3
# brute-forcePdfPasswordBreaker
'''
Say you have an encrypted PDF that you have forgotten the password to, but you remember it was a single English word. Trying to guess your forgotten password is quite a boring task. Instead you can write a program that will decrypt the PDF by trying every possible English word until it finds one that works. This is called a brute-force password attack. Download the text file dictionary.txt from http://nostarch.com/automatestuff/. This dictionary file contains over 44,000 English words with one word per line.
Using the file-reading skills you learned in Chapter 8, create a list of word strings by reading this file. Then loop over each word in this list, passing it to the decrypt() method. If this method returns the integer 0, the password was wrong and your program should continue to the next password. If decrypt() returns 1, then your program should break out of the loop and print the hacked password. You should try both the uppercase and lower-case form of each word. (On my laptop, going through all 88,000 uppercase and lowercase words from the dictionary file takes a couple of minutes. This is why you shouldn’t use a simple English word for your passwords.)
'''
# Usage: python brute-forcePdfPasswordBreaker.py file
import sys
import PyPDF2
if len(sys.argv) < 3:
print('Usage: python brute-forcePdfPasswordBreaker.py pdf_file dictionary')
sys.exit()
pdf = sys.argv[1]
pdfReader = PyPDF2.PdfFileReader(open(pdf, 'rb'))
dictionary = sys.argv[2]
file = open(dictionary, 'r')
lines = file.readlines()
for line in lines:
password = line.strip()
if pdfReader.decrypt(password) is 1:
print('Password: ' + password)
break
<file_sep>/Chapter 17/identifyingPhotoFoldersOnTheHardDrive.py
#! python 3
# identifyingPhotoFolderOnTheHardDrive.py
'''
I have a bad habit of transferring files from my digital camera to temporary folders somewhere on the hard drive and then forgetting about these folders. It would be nice to write a program that could scan the entire hard drive and find these leftover “photo folders.”
Write a program that goes through every folder on your hard drive and finds potential photo folders. Of course, first you’ll have to define what you consider a “photo folder” to be; let’s say that it’s any folder where more than half of the files are photos. And how do you define what files are photos?
First, a photo file must have the file extension .png or .jpg. Also, photos are large images; a photo file’s width and height must both be larger than 500 pixels. This is a safe bet, since most digital camera photos are several thousand pixels in width and height.
As a hint, here’s a rough skeleton of what this program might look like:
#! python3 #
Import modules and write comments to describe this program.
for foldername, subfolders, filenames in os.walk('C:\\'):
numPhotoFiles = 0
numNonPhotoFiles = 0
for filename in filenames:
# Check if file extension isn't .png or .jpg.
if TODO:
numNonPhotoFiles += 1
continue # skip to next filename
# Open image file using Pillow.
# Check if width & height are larger than 500.
if TODO:
# Image is large enough to be considered a photo.
numPhotoFiles += 1
else:
# Image is too small to be a photo.
numNonPhotoFiles += 1
# If more than half of files were photos,
# print the absolute path of the folder.
if TODO:
print(TODO)
When the program runs, it should print the absolute path of any photo folders to the screen.
'''
# Usage: python identifyingPhotoFolderOnTheHardDrive.py
import os
from PIL import Image
for foldername, subfolders, filenames in os.walk('C:\\'):
numPhotoFiles = 0
numNonPhotoFiles = 0
for filename in filenames:
# Check if file extension isn't .png or .jpg.
if not (filename.endswith('.png') or filename.endswith('.jpg')):
numNonPhotoFiles += 1
continue # skip to next filename
# Open image file using Pillow.
im = Image.open(filename)
width, height = im.size
# Check if width & height are larger than 500.
if width > 500 and height > 500:
# Image is large enough to be considered a photo.
numPhotoFiles += 1
else:
# Image is too small to be a photo.
numNonPhotoFiles += 1
# If more than half of files were photos,
# print the absolute path of the folder.
if numPhotoFiles >= numNonPhotoFiles:
print(os.path.abspath(foldername))
<file_sep>/Chapter 18/lookingBusy.py
#! python3
# lookingBusy.py
'''
Many instant messaging programs determine whether you are idle, or away from your computer, by detecting a lack of mouse movement over some period of time—say, ten minutes. Maybe you’d like to sneak away from your desk for a while but don’t want others to see your instant messenger status go into idle mode. Write a script to nudge your mouse cursor slightly every ten seconds. The nudge should be small enough so that it won’t get in the way if you do happen to need to use your computer while the script is running.
'''
# Usage: python lookingBusy.py
import pyautogui
import time
print('Press Ctrl-C to quit.')
try:
while True:
time.sleep(10)
pyautogui.moveRel(2, 0, duration=0.25)
pyautogui.moveRel(-2, 0, duration=0.25)
except KeyboardInterrupt:
print('Done.')
<file_sep>/Chapter 12/spreadsheetToTextFiles.py
#! python3
# spreadsheetToTextFiles.py
'''
Write a program that performs the tasks of the previous program in reverse order: The program should open a spreadsheet and write the cells of column A into one text file, the cells of column B into another text file, and so on.
'''
# Usage: python spreadsheetToTextFiles.py fileName
import openpyxl
import sys
if len(sys.argv) < 2:
print('Usage: python spreadsheetToTextFiles.py fileName')
sys.exit()
file = sys.argv[1]
wbRead = openpyxl.load_workbook(file)
readSheet = wbRead.active
columnNumber = 1
for i in range(1, readSheet.max_column+1):
file = open(str(columnNumber) + '.txt', 'w')
for j in range(1, readSheet.max_row+1):
if readSheet.cell(row=j, column=i).value is not None:
file.write(str(readSheet.cell(row=j, column=i).value))
file.close()
columnNumber += 1
<file_sep>/Chapter 15/prettifiedStopwatch.py
#! python3
# prettifiedStopwatch.py
'''
Expand the stopwatch project from this chapter so that it uses the rjust() and ljust() string methods to “prettify” the output. (These methods were covered in Chapter 6.) Instead of output such as this:
Lap #1: 3.56 (3.56)
Lap #2: 8.63 (5.07)
Lap #3: 17.68 (9.05)
Lap #4: 19.11 (1.43)
... the output will look like this:
Lap # 1: 3.56 ( 3.56)
Lap # 2: 8.63 ( 5.07)
Lap # 3: 17.68 ( 9.05)
Lap # 4: 19.11 ( 1.43)
Note that you will need string versions of the lapNum, lapTime, and totalTime integer and float variables in order to call the string methods on them.
Next, use the pyperclip module introduced in Chapter 6 to copy the text output to the clipboard so the user can quickly paste the output to a text file or email.
'''
# Usage: python prettifiedStopwatch.py
import time
import pyperclip
print('Press ENTER to begin. Afterwards, press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input() # press Enter to begin
print('Started.')
startTime = time.time() # get the first lap's start time
lastTime = startTime
lapNum = 1
lines = ''
try:
while True:
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
lines += 'Lap #%s: %s (%s)' % (str(lapNum).rjust(2), str(totalTime).rjust(5), str(lapTime).rjust(6)) + '\n'
print('Lap #%s: %s (%s)' % (str(lapNum).rjust(2), str(totalTime).rjust(5), str(lapTime).rjust(6)), end='')
lapNum += 1
lastTime = time.time() # reset the last lap time
except KeyboardInterrupt:
# Handle the Ctrl-C exception to keep its error message from displaying.
pyperclip.copy(lines)
print('\nDone.')
<file_sep>/Chapter 12/multiplicationTableMaker.py
#! python3
# multiplicationTableMaker.py
'''
Create a program multiplicationTable.py that takes a number N from the command line and creates an N×N multiplication table in an Excel spreadsheet.
Row 1 and column A should be used for labels and should be in bold.
'''
# Usage: python multiplicationTableMaker.py number
import openpyxl
from openpyxl.styles import Font
import sys
if len(sys.argv) < 2:
print('Usage: python multiplicationTableMaker.py number')
sys.exit()
n = int(sys.argv[1])
if n < 1:
print('Invalid input.')
sys.exit()
wb = openpyxl.Workbook()
activeSheet = wb.active
boldObj = Font(bold=True)
for i in range(1, n+1):
activeSheet.cell(row=1, column=i+1).value = i
activeSheet.cell(row=1, column=i+1).font = boldObj
activeSheet.cell(row=i + 1, column=1).value = i
activeSheet.cell(row=i + 1, column=1).font = boldObj
for i in range(1, n+1):
for j in range(1, n+1):
activeSheet.cell(row=i+1, column=j+1).value = activeSheet.cell(row=i+1, column=1).value * activeSheet.cell(row=1, column=j+1).value
wb.save('multiplicationTable.xlsx')
<file_sep>/Chapter 12/blankRowInserter.py
#! python3
# blankRowInserter.py
'''
Create a program blankRowInserter.py that takes two integers and a filename string as command line arguments. Let's call the first integer N and the second interger M. Starting at row N, the program should insert M blank rows into the spreadsheet.
You can write this program by reading in the contents of the spreadsheet. Then, when writing out the new spreadsheet, use a for loop to copy the first N lines, for the remaining lines, add M to the row number in the output spreadsheet.
'''
# Usage: python blankRowInserter.py rowNumber numberOfBlankRows fileName
import openpyxl
import sys
if len(sys.argv) < 4:
print('Usage: python blankRowInserter.py rowNumber numberOfBlankRows fileName')
sys.exit()
n = int(sys.argv[1])
m = int(sys.argv[2])
file = sys.argv[3]
if n < 1 or m < 1:
print('Invalid input.')
sys.exit()
wbRead = openpyxl.load_workbook(file)
readSheet = wbRead.active
wbWrite = openpyxl.Workbook()
writeSheet = wbWrite.active
for rowOfReadCellObjects in readSheet[readSheet.cell(row=1, column=1).coordinate:readSheet.cell(row=readSheet.max_row, column=readSheet.max_column).coordinate]:
for readCell in rowOfReadCellObjects:
if readCell.row < m - 1:
writeSheet.cell(row=readCell.row, column=readCell.column).value = readCell.value
else:
writeSheet.cell(row=readCell.row+m, column=readCell.column).value = readCell.value
wbWrite.save('blankRowInserted.xlsx')
<file_sep>/Chapter 6/tablePrinter.py
#! python3
# tablePrinter.py
'''
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
Your printTable() function would print the following:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Hint: Your code will first have to find the longest string in each of the inner lists so that the whole column can be wide enough to fit all the strings. You can store the maximum width of each column as a list of integers. The printTable() function can begin with colWidths = [0] * len(tableData), which will create a list containing the same number of 0 values as the number of inner lists in tableData. That way, colWidths[0] can store the width of the longest string in tableData[0], colWidths[1] can store the width of the longest string in tableData[1], and so on. You can then find the largest value in the colWidths list to find out what integer width to pass to the rjust() string method.
'''
# Usage: python tablePrinter.py
def printTable(data):
colWidths = [0] * len(data)
for i in range(len(data)):
colWidths[i] = len(max(data[i], key=len))
amount = int(max(colWidths))
for i in range(len(data[0])):
for j in range(len(data)):
print(data[j][i].rjust(amount), end="")
print('\n')
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
<file_sep>/Chapter 8/madLibs.py
#! python3
# madLibs.py
'''
Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
The program would find these occurrences and prompt the user to replace them.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
'''
# Usage: python madLibs.py input_file [output_file]
import sys, re
if len(sys.argv) < 2:
print('Usage: python madLibs.py input_file [output_file]')
infile = open(sys.argv[1], 'r')
if len(sys.argv) > 2:
outfile = open(sys.argv[2], 'w')
else:
outfile = open('output.txt', 'w')
wordRegex = re.compile(r'\w+')
for line in infile:
for word in line.split():
source = wordRegex.search(word)
if source.group() == 'ADJECTIVE':
print('Enter an adjective:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'NOUN':
print('Enter a noun:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'ADVERB':
print('Enter an adverb:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'VERB':
print('Enter an verb:')
newWord = raw_input()
line = line.replace(source.group(), newWord)
outfile.write(line)
infile.close()
outfile.close()
print('Output:')
outfile = open('output.txt', 'r')
print outfile.read()
outfile.close()
<file_sep>/Chapter 11/linkVerification.py
#! python3
# linkVerification.py
'''
Write a program that, given the URL of a web page, will attempt to download every linked page on the page. The program should flag any pages that have a 404 “Not Found” status code and print them out as broken links.
'''
# Usage: python linkVerification.py site_url
from selenium import webdriver
import sys
if len(sys.argv) < 2:
print('Usage: python linkVerification.py site_url")
sys.exit()
siteUrl = sys.argv[1]
print('Opening Firefox...')
browser = webdriver.Firefox()
print('Opening ' + siteUrl + '...')
browser.get(siteUrl)
print('Downloading linked pages...')
linkElements = browser.find_elements_by_tag_name('a')
for i in range (linkElements)
print('Closing Firefox...')
browser.quit()
print('Done')
<file_sep>/Chapter 11/commandLineEmailer.py
#! python3
# commandLineEmailer.py - untested
'''
Write a program that takes an email address and string of text on the command line and then, using Selenium, logs into your email account and sends an email of the string to the provided address. (You might want to set up a separate email account for this program.)
This would be a nice way to add a notification feature to your programs. You could also write a similar program to send messages from a Facebook or Twitter account.
'''
# Usage: python commandLineEmailer.py email_address message_string
from selenium import webdriver
import sys
if len(sys.argv) < 3:
print('Usage: python commandLineEmailer.py email_address message_string")
sys.exit()
emailId = sys.argv[1]
messageString = sys.argv[2]
print('Opening Firefox...')
browser = webdriver.Firefox()
print('Opening Gmail...')
browser.get('https://gmail.com')
print('Signing in...')
signInElement = browser.find_element_by_link_text('Sign in')
signInElement.click()
usernameElement = browser.find_element_by_name('identifier')
usernameElement.send_keys(<EMAIL>)
usernameElement.send_keys(Keys.ENTER)
passwordElement = browser.find_element_by_name('password')
passwordElement.send_keys(<PASSWORD>)
passwordElement.send_keys(Keys.ENTER)
print('Composing email...')
emailElement = browser.find_element_by_class('T-I J-J5-Ji T-I-KE L3')
emailElement.click()
#toElement = browser.find_element_by_name('to')
emailElement.send_keys(emailId)
emailElement.send_keys(Keys.TAB)
#subjectElement = broswer.find_element_by_name('subjectelement')
emailElement.send_keys('Sent from the command line')
emailElement.send_keys(Keys.TAB)
#messageElement = browser.find_element_by_id(':am')
emailElement.send_keys(messageString)
emailElement.send_keys(Keys.TAB)
print('Sending email...')
emailElement.send_keys(Keys.ENTER)
print('Signing out...')
emailElement = browser.find_element_by_class('gb_x gb_Ea gb_f')
emailElement.click()
emailElement = browser.find_element_by_link_text('Sign out')
emailElement.click()
print('Closing Firefox...')
browser.quit()
print('Done')
<file_sep>/Chapter 9/selectiveCopy.py
#! python3
# selectiveCopy.py
'''
Write a program that walks through a folder tree and searches for files with a certain file extension (such as .pdf or .jpg). Copy these files from whatever location they are in to a new folder.
'''
# Usage: python selectiveCopy.py .extension
import sys, os, shutil
if len(sys.argv) < 2:
print('Usage: python selectiveCopy.py .extension')
sys.exit()
extension = sys.argv[1]
print('Enter source folder path: ')
sourceFolder = raw_input()
print('Enter destination folder path: ')
destinationFolder = raw_input()
print('\n')
for folderName, subfolders, filenames in os.walk(sourceFolder):
for filename in filenames:
if filename.endswith(extension):
filepath = os.path.join(folderName,filename)
shutil.copy(original, destinationFolder)
print('Copied ' + filepath + ' to ' + destinationFolder)
<file_sep>/Chapter 13/customInvitationsAsWordDocuments.py
#! python3
# customInvitationsAsWordDocuments.py
'''
Say you have a text file of guest names. This guests.txt file has one name per line, as follows:
<NAME>
<NAME>
<NAME>
<NAME>
Robocop
Write a program that would generate a Word document with custom invitations that look like Figure 13-11.
Since Python-Docx can use only those styles that already exist in the Word document, you will have to first add these styles to a blank Word file and then open that file with Python-Docx. There should be one invitation per page in the resulting Word document, so call add_break() to add a page break after the last paragraph of each invitation. This way, you will need to open only one Word document to print all of the invitations at once.
You can download a sample guests.txt file from http://nostarch.com/automatestuff/.
'''
# Usage: python customInvitationsAsWordDocuments.py guest_list
import sys
import docx
if len(sys.argv) < 2:
print('Usage: python customInvitationAsWordDocuments.py guests.txt')
sys.exit()
doc = docx.Document()
guestList = sys.argv[1]
file = open(guestList, 'r')
for line in file:
doc.add_heading('It would be a pleasure to have the company of', 0)
guest = doc.add_paragraph(line)
guest.style = 'Subtitle'
doc.add_heading('at 11010 Memory Lane on the Evening of', 1)
date = doc.add_paragraph('April 1st')
date.runs[0].underline = True
time = doc.add_paragraph('at 7 o\'clock')
time.runs[0].underline = True
time.runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
file.close()
doc.save('customInvitationsAsWordDocuments.docx')
| f11cd7c3a0ed525887e2affec9436f8a5fa96a30 | [
"Markdown",
"Python"
] | 28 | Python | s-anusha/automatetheboringstuff | 0bf3fc56836654d331d4a5450736cc808059865e | 5db8a442e3eea69a943a34d68b603b1bb5879949 |
refs/heads/master | <file_sep><?php
namespace Ragnaroq\Base;
use Ragnaroq\App\Runner;
use Symfony\Component\HttpFoundation\Request;
/**
* Class BaseView
* @package Ragnaroq\View
*/
class BaseView
{
/** @var BaseModel */
protected $model;
/** @var Request */
protected $request;
/**
* BaseView constructor.
*
* @param $model BaseModel Model that will be rendered by this view
*/
public function __construct(BaseModel $model)
{
$this->model = $model;
$this->request = empty(Runner::$request)
? Request::createFromGlobals()
: Runner::$request;
}
/**
* Sets the template to be used in the view.
*
* @param $templateName string Name of the template inside the base
* template directory without the extension, for example: "Folder\File",
* "Folder/Folder/File" or simply "File"
* @return string
*/
public function getViewTemplate($templateName)
{
return Runner::getViewDir() . "/$templateName.php";
}
/**
* Gets the base template
*/
public function getBaseTemplate()
{
return Runner::getTemplateDir() . "/Base.php";
}
/**
* Must output the final HTML page with Model data
* previously processed by the Controller
*
* @return void
*/
/**
* Output the view passing the model data
*
* @param $viewName string View template name
* @param $viewData array Array containing variables to be used in the view
*/
public function render($viewName, $viewData = array())
{
$templateFile = $this->getViewTemplate($viewName);
$_viewContent = $this->renderToString($templateFile, $viewData);
extract($viewData);
require $this->getBaseTemplate();
}
/**
* Renders a parsed PHP template to a string
*
* @param $file string Absolute file path
* @param $vars array Variables to be used in the PHP template
* @return string
*/
private function renderToString($file, $vars = null)
{
if (is_array($vars) && !empty($vars))
extract($vars);
ob_start();
include $file;
return ob_get_clean();
}
}
<file_sep><?php
namespace Ragnaroq\Controller;
use Ragnaroq\Base\BaseController;
use Ragnaroq\Model\ExampleModel;
/**
* In a controller you must define the actions of your web app,
* in each action you handle the corresponding model for the
* controller or any other model you need to instantiate.
*
* Class ExampleController
* @package Ragnaroq\Controller
*/
class ExampleController extends BaseController
{
/**
* Just set the name and lastname for the ExampleModel
* that will be showed in the view.
*/
public function greet()
{
$this->model->name = "Salvador";
$this->model->lastname = "Pasquier";
$this->view->render("Example/Welcome");
}
}
<file_sep><?php
namespace Ragnaroq\App;
use OAuth2\Client;
use Ragnaroq\App\Config;
use Symfony\Component\HttpFoundation\Request;
class Session
{
private $req;
private $storage;
/**
* Session constructor.
*
* @param Request $request
*/
public function __construct(Request $request)
{
$this->req = $request;
$this->storage = $request->getSession();
}
/**
* Reads a value stored int the session by its unique key
*
* @param $valueKey string Unique key that identifies the stored value
* @param $defaultValue string Default value if there isn't a value with the given key
* @return mixed
*/
public function read($valueKey, $defaultValue = null)
{
return $this->storage->get($valueKey, $defaultValue);
}
/**
* Stores a value in the session identifying it with a unique key
*
* @param $valueKey string Unique key to identify the stored value
* @param $value mixed Value to be saved in the Session
*/
public function store($valueKey, $value)
{
$this->storage->set($valueKey, $value);
}
/**
* Removes a value stored in the session that has the given key
*
* @param $valueKey string Unique key that identifies the value to be removed
*/
public function delete($valueKey)
{
$this->storage->remove($valueKey);
}
/**
* Requests an OAuth2 access token and saves it in the Session
* as an array representing the response and with key "accessToken".
*
* @param $code
* @throws \OAuth2\Exception
*/
public function requestOAuth2AccessToken($code)
{
// Get OAuth2 settings
$accessTokenUrl = Config::get('oauth.access_token_url');
$clientId = Config::get('oauth.client');
$clientSecret = Config::get('oauth.secret');
$redirectUrl = Config::get('oauth.redirect_uri');
$userAgent = Config::get('oauth.user_agent');
// Prepare OAuth2 client
$client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);
// Get access token
$accessTokenResult = $this->read('accessToken');
if (null == $accessTokenResult) {
$params = array('code' => $code, "redirect_uri" => $redirectUrl);
$response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params);
$accessTokenResult = $response["result"];
$this->store('accessToken', $accessTokenResult);
}
// How to request any resource from Reddit
// $client->setAccessToken($accessTokenResult["access_token"]);
// $client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER);
// $this->model->response = $client->fetch("https://oauth.reddit.com/api/v1/me.json");
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="charset=utf-8">
<title><?= !empty($pageTitle) ? $pageTitle : "SV Giveaway-er App" ?></title>
<?= !empty($styles) ? $styles : '' ?>
</head>
<body>
<?= $_viewContent ?>
<?= !empty($scripts) ? $scripts : '' ?>
</body>
</html><file_sep><?php
namespace Ragnaroq\Model;
use Ragnaroq\Base\BaseModel;
/**
* Here you can define any data needed for your homepage.
*
* Class HomeModel
* @package Ragnaroq\Model
*/
class HomeModel extends BaseModel
{
public $response;
}
<file_sep><?php
namespace Ragnaroq\App;
class Config
{
private $settings;
/** @var Config $instance */
private static $instance = null;
/**
* Config constructor.
*/
private function __construct()
{
$this->settings = require Runner::getConfigDir() . "/settings.php";
}
/**
* Gets the value of a configuration.
*
* @param $configName string Name of the configuration property
* @param $defaultValue string Default value of the configuration in case it hasn't been set
* @return string
*/
public static function get($configName, $defaultValue = null)
{
if (null === Config::$instance) {
Config::$instance = new Config();
}
return isset(Config::$instance->settings[$configName])
? Config::$instance->settings[$configName]
: $defaultValue;
}
}
<file_sep><?php
/**
* Which method in which MVC set will be executed
* for each defined action in this array.
*/
$actions = array(
'index' => \Ragnaroq\App\Runner::mvcAction('Home', 'index'),
'welcome' => \Ragnaroq\App\Runner::mvcAction('Example', 'greet'),
'authorize' => \Ragnaroq\App\Runner::mvcAction('OAuth2', 'authorizeCallback'),
);
/**
* Which of the previously defined actions will
* be executed in each route.
*/
$routes = array(
'GET' => array(
'/' => $actions['index'],
'/example' => $actions['welcome'],
'/authorize_callback' => $actions['authorize'],
),
'POST' => array(
),
'DELETE' => array(
),
'PUT' => array(
),
'OPTIONS' => array(
),
);
return $routes;
<file_sep># Test app that logins to reddit account using OAuth2
Also implements MVC to organize code, following this guide:
[how to implement the MVC pattern in PHP](http://www.sitepoint.com/the-mvc-pattern-and-php-2/).
<file_sep><h1>Reddit Profile</h1>
<table>
<tbody>
<tr>
<td><strong>Name</strong></td>
<td><?= $me['name'] ?></td>
</tr>
<tr>
<td><strong>Registered (UTC)</strong></td>
<td><?= date('Y-m-d H:i:s', $me['created_utc']) ?></td>
</tr>
<tr>
<td><strong>Link Karma</strong></td>
<td><?= $me['link_karma'] ?></td>
</tr>
<tr>
<td><strong>Comment Karma</strong></td>
<td><?= $me['comment_karma'] ?></td>
</tr>
<tr>
<td><strong>Over 18?</strong></td>
<td><?= $me['over_18'] ? 'Yes' : 'No' ?></td>
</tr>
</tbody>
</table>
<file_sep><?php
namespace Ragnaroq\Base;
use Ragnaroq\App\Runner;
class HtmlPage
{
public static function renderError4xx($code, $message)
{
require Runner::getTemplateDir() . "/Error4xx.php";
}
public static function renderError5xx($code, $message)
{
require Runner::getTemplateDir() . "/Error5xx.php";
}
}<file_sep><?php
namespace Ragnaroq\App;
use Ragnaroq\Base\BaseController;
use Ragnaroq\Base\BaseModel;
use Ragnaroq\Base\BaseView;
use Ragnaroq\Base\HtmlPage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
class Runner
{
/** @var Request */
public static $request;
/**
* Runner constructor.
*/
public function __construct()
{
static::$request = Request::createFromGlobals();
if (!static::$request->hasPreviousSession())
{
$session = new Session();
$session->start();
static::$request->setSession($session);
}
}
/**
* Starts the application
*/
public function start()
{
$page = static::$request->get('path', '/');
$method = static::$request->getMethod();
try
{
if (!empty($page) && !empty($method))
{
$routes = require Runner::getConfigDir() . "/routes.php";
foreach ($routes as $method_key => $route) {
if ($method == $method_key) {
foreach ($route as $key => $components) {
if ($page == $key) {
$model = $components['model'];
$controller = $components['controller'];
$action = $components['action'];
break;
}
}
}
}
if (isset($model, $controller, $action))
{
/** @var BaseModel $routeModel */
$routeModel = new $model();
$routeView = new BaseView($routeModel);
/** @var BaseController $routeController */
$routeController = new $controller($routeModel, $routeView);
if (method_exists($routeController, $action))
{
$routeController->beforeAction();
$routeController->$action();
$routeController->afterAction();
}
else
{
HtmlPage::renderError5xx(500, "Bad backend configuration!");
}
}
else
{
HtmlPage::renderError4xx(404, "Page not found!");
}
}
else
{
HtmlPage::renderError4xx(400, "Bad request!");
}
}
catch(\Exception $e)
{
syslog(LOG_ALERT, "[{$e->getCode()}] SVEggGiverApp: Fatal error."
. "{$e->getMessage()}. Error trace: {$e->getTraceAsString()}");
HtmlPage::renderError5xx(500, "Server was destroyed!");
}
}
/**
* Generates an array with the MVC set and the specific action that will
* be executed when an user access an specific route of this app.
*
* @param $prefix string Prefix of the classes for the MVC pattern
* @param $action string Name of the Controller method that will be executed
* @return array
*/
public static function mvcAction($prefix, $action)
{
return array(
'model' => "Ragnaroq\\Model\\" . $prefix . 'Model',
'controller' => "Ragnaroq\\Controller\\" . $prefix . 'Controller',
'action' => $action
);
}
/**
* Gets the absolute directory of the app.
*
* @return string
*/
public static function getAppDir()
{
return dirname(dirname(dirname(__DIR__)));
}
/**
* Gets the absolute directory of the configuration for the app.
*
* @return string
*/
public static function getConfigDir()
{
return Runner::getAppDir() . "/config";
}
public static function getViewDir()
{
return dirname(__DIR__) . "/View";
}
/**
* Gets the absolute directory that contains php-html templates
*
* @return string
*/
public static function getTemplateDir()
{
return dirname(__DIR__) . "/Template";
}
}
<file_sep><?php
namespace Ragnaroq\Model;
use Ragnaroq\Base\BaseModel;
/**
* Class OAuthModel
* @package Ragnaroq\Model
*/
class OAuth2Model extends BaseModel
{
}
<file_sep><strong>Redirecting you as part of the OAuth2 authentication process...</strong><file_sep><?php
namespace Ragnaroq\Base;
use Ragnaroq\App\Session;
use Ragnaroq\App\Runner;
use Symfony\Component\HttpFoundation\Request;
/**
* Class BaseController
* @package Ragnaroq\Controller
*/
class BaseController
{
/** @var BaseModel $model */
protected $model;
/** @var BaseView $view */
protected $view;
/** @var Request $request */
protected $request;
/** @var Session $session */
protected $session;
/**
* BaseController constructor.
*
* @param BaseModel $model Model that will be handled by this Controller
* @param BaseView $view View that will be rendered by this Controller
*/
public function __construct(BaseModel $model, BaseView $view)
{
$this->model = $model;
$this->view = $view;
$this->request = empty(Runner::$request)
? Request::createFromGlobals()
: Runner::$request;
$this->session = new Session($this->request);
}
/**
* The micro-framework call this function
* before every action of the Controller.
*/
public function beforeAction()
{
}
/**
* The micro-framework calls this function
* after every action of the Controller.
*/
public function afterAction()
{
}
}
<file_sep><h1>Hello <?= $this->model->name . ' ' . $this->model->lastname ?>!</h1>
<file_sep><?php
namespace Ragnaroq\Base;
/**
* Class BaseModel
* @package Ragnaroq\Model
*/
abstract class BaseModel
{
}
<file_sep><?php
namespace Ragnaroq\Controller;
use OAuth2\Client;
use Ragnaroq\App\Config;
use Ragnaroq\Base\BaseController;
/**
* This is the standard controller of this micro-framework,
* you can use it to render the homepage of the app.
*
* Class HomeController
* @package Ragnaroq\Controller
*/
class HomeController extends BaseController
{
/**
* Here you can render the homepage of the app
*/
public function index()
{
// Get OAuth2 parameters from config and session
$clientId = Config::get('oauth.client');
$clientSecret = Config::get('oauth.secret');
$userAgent = Config::get('oauth.user_agent');
$accessTokenResult = $this->session->read('accessToken');
// Setup OAuth2 client to request resources from Reddit
$client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);
$client->setAccessToken($accessTokenResult["access_token"]);
$client->setAccessTokenType(Client::ACCESS_TOKEN_BEARER);
// Request user response
$response = $client->fetch("https://oauth.reddit.com/api/v1/me.json");
$this->view->render("Home", array(
'me' => $response['result'],
'pageTitle' => 'Reddit profile example'
));
}
public function beforeAction()
{
// If there isn't an access token in the Session start a new OAuth2 flow
$accessTokenResult = $this->session->read('accessToken');
if (empty($accessTokenResult)) {
$this->session->store('returnUrl', $this->request->getUri());
header('Location: /authorize_callback');
exit;
}
}
}
<file_sep><?php
$settings = array();
$settings['oauth.authorization_url'] = 'https://ssl.reddit.com/api/v1/authorize';
$settings['oauth.access_token_url'] = 'https://ssl.reddit.com/api/v1/access_token';
$settings['oauth.client'] = 'xSDj20h3AKfhxw';
$settings['oauth.secret'] = '<KEY>';
$settings['oauth.redirect_uri'] = "http://svapp.triparticion.xyz/authorize_callback";
$settings['oauth.user_agent'] = 'SVEggGiverApp/0.1 by ragnaroq';
return $settings;
<file_sep><?php
namespace Ragnaroq\Controller;
use Ragnaroq\App\Config;
use Ragnaroq\App\Page\HtmlPage;
use Ragnaroq\Base\BaseController;
use OAuth2\Client;
/**
* Class HomeController
* @package Ragnaroq\Controller
*/
class OAuth2Controller extends BaseController
{
public function authorizeCallback()
{
// If there is an error parameter, show that error
$error = $this->request->get('error');
if (!empty($error)) {
HtmlPage::renderError5xx(500, "<pre>OAuth Error: "
. $this->request->get('error') . "\n"
. '<a href="/authorize_callback">Retry</a></pre>');
return;
}
// Get OAuth2 settings
$authorizeUrl = Config::get('oauth.authorization_url');
$clientId = Config::get('oauth.client');
$clientSecret = Config::get('oauth.secret');
$redirectUrl = Config::get('oauth.redirect_uri');
$userAgent = Config::get('oauth.user_agent');
// Prepare OAuth2 client to request an authorization code
$client = new Client($clientId, $clientSecret, Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);
// Request an authorization code if there isn't one in the GET
// parameter code, if there is one, request an access token
$code = $this->request->get('code');
if (empty($code))
{
$this->session->delete('accessToken');
$authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array(
'scope' => 'identity',
'state' => 'As64xA3ueT6sjxiazAA7278yhs6103jx',
'duration' => 'permanent'
));
header('Location: ' . $authUrl);
}
else
{
$this->session->requestOAuth2AccessToken($code);
header('Location: /');
return;
}
}
}
<file_sep><?php
namespace Ragnaroq\Model;
use Ragnaroq\Base\BaseModel;
/**
* In the model you just need to define which data will need to be accessed
* by your controllers or showed by the views.
*
* Class ExampleModel
* @package Ragnaroq\Model
*/
class ExampleModel extends BaseModel
{
public $name;
public $lastName;
}
<file_sep><?php
require "../vendor/autoload.php";
use Ragnaroq\App\Runner;
$runner = new Runner();
$runner->start();
| 615d08ce31012d38ed470a2d6a3f7e7688760f8b | [
"Markdown",
"PHP"
] | 21 | PHP | spasquier/sv-egg-giver | 731f7df95e73747768c7df70e7ca85c4cf379f64 | 1fbe7d803e59908dda7681d032e8d04209c95fbb |
refs/heads/dev | <repo_name>RomanShabanov/Node-Express-Sockets-MongoDB<file_sep>/src/middlewares/common.middleware.ts
import express, { Router, Request, Response, NextFunction } from "express";
import cors from "cors";
import parser from "body-parser";
import compression from "compression";
import path from "path";
import { isProd } from "../config/variables";
import { expressLogger } from "../utils/logger";
export const handleStaticFiles = (router: Router) => {
console.log(__dirname);
router.use(
express.static(path.join(__dirname, "../../static"), { dotfiles: "allow" })
);
};
export const handleCors = (router: Router) =>
router.use(cors({ credentials: true, origin: true }));
export const handleBodyRequestParsing = (router: Router) => {
router.use(parser.urlencoded({ extended: true }));
router.use(parser.json());
};
/** TODO: Compression should be handled by NGINX. Node is single-threaded and compression is CPU intensive task. */
export const handleCompression = (router: Router) => {
router.use(compression());
};
export const handleHeanders = (router: Router) => {
router.use((req: Request, res: Response, next: NextFunction) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader(
"Access-Control-Allow-Headers",
"Access-Control-Allow-Origin,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization"
);
next();
});
};
export const handleLogging = (router: Router) => {
if (isProd) {
router.use(expressLogger);
}
};
export default [
handleStaticFiles,
handleCors,
handleBodyRequestParsing,
handleCompression,
handleHeanders
];
<file_sep>/src/master.ts
import cluster from "cluster";
import os from "os";
if (cluster.isMaster) {
masterProcess();
} else {
childProcess();
}
function masterProcess() {
console.log(`Master ${process.pid} is running`);
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
console.log(`Forking process number ${i}...`);
cluster.fork();
}
process.exit();
}
function childProcess() {
console.log(`Worker ${process.pid} started and finished`);
process.exit();
}
<file_sep>/src/services/v1/users/users.controller.ts
import Users, { IUser } from "./users.model";
import to from "../../../utils/await";
import User from "./users.model";
export async function getUsers(): Promise<IUser[]> {
return await Users.find()
.lean()
.exec();
}
export async function getUserById(id: IUser["_id"]): Promise<IUser | null> {
const [err, user] = await to<IUser>(
Users.findById(id)
.lean()
.exec()
);
if (err || !user) {
return null;
}
return user;
}
export async function createUser(data: any): Promise<IUser | null> {
const [err, user] = await to(User.create(data));
if (+err.code === 11000) {
console.log("duplicate");
}
return user;
}
<file_sep>/docker-compose.yml
version: "3.3"
services:
# https://certbot.eff.org/lets-encrypt/osx-nginx
# https://dev.to/domysee/setting-up-a-reverse-proxy-with-nginx-and-docker-compose-29jg
#
# nginx:
# image: nginx:latest
# container_name: production_nginx
# - NGINX_HOST=foobar.com
# - NGINX_PORT=80
# volumes:
# - ./nginx.conf:/etc/nginx/nginx.conf
# - ./nginx/error.log:/etc/nginx/error_log.log
# - ./nginx/cache/:/etc/nginx/cache
# - /etc/letsencrypt/:/etc/letsencrypt/
# ports:
# - 80:80
# - 443:443
redis:
image: redis
container_name: Redis-Cache
expose:
- 6379
mongo1:
hostname: mongo1
container_name: MongoDB-Primary
image: mongo:latest
expose:
- 27017
ports:
- 27017:27017
restart: always
entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"]
volumes:
- db-data:/data/db
- mongo-config:/data/configdb
mongo2:
hostname: mongo2
container_name: MongoDB-Secondary-1
image: mongo:latest
expose:
- 27017
ports:
- 27018:27017
restart: always
entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"]
mongo3:
hostname: mongo3
container_name: MongoDB-Secondary-2
image: mongo:latest
expose:
- 27017
ports:
- 27019:27017
restart: always
entrypoint: ["/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0"]
volumes:
db-data:
mongo-config:
<file_sep>/hosts.sh
#!/bin/bash
for entry in "mongo1" "mongo2" "mongo3" "localserver.com"
do
echo "Updating host entry: 127.0.0.1 $entry"
# find existing instances in the host file and save the line numbers
matches_in_hosts="$(grep -n $entry /etc/hosts | cut -f1 -d:)"
host_entry="127.0.0.1 $entry"
if [ ! -z "$matches_in_hosts" ]
then
# iterate over the line numbers on which matches were found
while read -r line_number; do
# replace the text of each line with the desired host entry
sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts
done <<< "$matches_in_hosts"
else
echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null
fi
done
<file_sep>/src/services/v1/pets/pets.routes.ts
import express, { Request, Response, NextFunction } from "express";
import Pets from "./pets.model";
const Router = express.Router();
Router.route("/").get((req: Request, res: Response, next: NextFunction) => {
Pets.find().then(pets => {
res.status(200).json({
payload: pets,
status: {
success: true,
code: 200
}
});
});
});
export default Router;
<file_sep>/Makefile
all: start-mongo-rs secure-connection
issue-certificate:
@sudo openssl genrsa -out ./security/localhost.key 2048
@sudo openssl req -new -x509 -key ./security/localhost.key -out ./security/localhost.crt -days 3650 -subj /CN=localhost
@sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./security/localhost.crt
MONGO_SCRIPT := $(shell cat ./replica_set.config)
start-mongo-rs:
@echo "Starting MongoDB Replica Set (localhost:27017)"
@docker-compose -f ./docker-compose.yml up -d
@echo Wait...
@sleep 15
@docker exec -it MongoDB-Primary mongo --eval "$(MONGO_SCRIPT)"
@docker exec -it MongoDB-Primary mongo --eval "rs.status()"
@sh hosts.sh
@docker-compose ps
@echo "\033[92mDone.\033[0m"
@echo "\033[92mMongoDB connection string: mongodb://localhost:27017,localhost:27018,localhost:27019/database?replicaSet=rs0\033[0m"
secure-connection:
@echo "Create certificates for secure connection"
openssl req -nodes -new -x509 -keyout ./security/server.key -out ./security/server.cert<file_sep>/src/services/v1/pets/pets.model.ts
import mongoose, { Schema, Document } from "mongoose";
import { IUser } from "../users/users.model";
export interface IPet extends Document {
name: string;
owner: IUser["_id"];
}
const PetSchema: Schema = new Schema({
name: { type: String, required: true },
owner: { type: Schema.Types.ObjectId }
});
const Pets = mongoose.model<IPet>("Pet", PetSchema);
Pets.find().then(pets => {
if (!pets.length) {
Pets.create([
{
name: "Milana"
}
]);
}
});
export default Pets;
<file_sep>/src/config/database.ts
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import bold from "chalk";
const { cyan: info, yellow: warning, red: error, magenta: fatal } = bold;
import { MONGODB_URI, isTest } from "./variables";
export default async () => {
const mongooseOpts = {
autoReconnect: true,
reconnectTries: 3,
reconnectInterval: 1000,
useNewUrlParser: true,
useCreateIndex: true, // Set to true to make Mongoose's default index build use createIndex() instead of ensureIndex() to avoid deprecation warnings from the MongoDB driver.
useFindAndModify: false // Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify()
};
const connection_string = isTest
? await new MongoMemoryServer().getConnectionString()
: MONGODB_URI;
mongoose.connect(connection_string, mongooseOpts);
mongoose.connection.on("connected", () => {
console.log(
info("Mongoose default connection is open to ", connection_string)
);
});
mongoose.connection.on("error", (err: any) => {
console.log(
warning("Mongoose default connection has occured " + err + " error")
);
});
mongoose.connection.on("disconnected", () => {
console.log(error("Mongoose default connection is disconnected"));
});
process.on("SIGINT", () => {
mongoose.connection.close(() => {
console.log(
fatal(
"Mongoose default connection is disconnected due to application termination"
)
);
process.exit(0);
});
});
};
<file_sep>/src/middlewares/routes.middleware.ts
import { Router } from "express";
import routes from "../services/v1/routes";
export const routes_v1 = (router: Router) => {
router.use("/v1", routes);
};
export default [routes_v1];
<file_sep>/src/config/variables.ts
require("dotenv").config();
export const MONGODB_URI = process.env.MONGODB_URI;
export const NODE_ENV = process.env.NODE_ENV;
export const isDev = process.env.NODE_ENV === "dev";
export const isTest = process.env.NODE_ENV === "test";
export const isProd = process.env.NODE_ENV === "prod";
export const JWT_SECRET = process.env.JWT_SECRET;
export const isSecure = process.env.HTTPS === "true";
<file_sep>/src/middlewares/checks.middleware.ts
import { Request, Response, NextFunction } from "express";
import { HTTP400Error } from "../utils/httpErrors";
import validator from "validator";
export const checkLoginParams = (
req: Request,
res: Response,
next: NextFunction
) => {
if (!req.body.email) {
throw new HTTP400Error("Missing email.");
}
if (!validator.isEmail(req.body.email)) {
throw new HTTP400Error("Email is incorrect.");
}
if (!req.body.password) {
throw new HTTP400Error("Missing password.");
}
next();
};
export const checkPasswordStrength = (
req: Request,
res: Response,
next: NextFunction
) => {
const password: string = req.body.password.toString();
if (!validator.isAlphanumeric(password)) {
throw new HTTP400Error("Password should contain letters and numbers.");
}
if (password.length < 8) {
throw new HTTP400Error("Password should be at least 8 characters long.");
}
};
export const checkMongoId = (
req: Request,
res: Response,
next: NextFunction
) => {
if (!validator.isMongoId(req.params.id)) {
throw new HTTP400Error("Invalid MongoDB ObjectId.");
}
next();
};
<file_sep>/src/services/v1/routes.ts
import express from "express";
import userRotes from "./users/users.routes";
import petsRotes from "./pets/pets.routes";
const Router = express.Router();
Router.use("/users", userRotes);
Router.use("/pets", petsRotes);
export default Router;
<file_sep>/README.md
# Node.js Boilerplate: Express + MongoDB + Typescript + Socket.IO + pm2
## Development
Step 1: Start the MongoDB replica cluster (1 Primary + 2 Secondary)
`make`
Step 2: Once asked enter root password to insert host entries into /etc/hosts
Step 3: Confirm that localhost:27017 runs primary instance
```
docker exec -it MongoDB-Primary mongo
rs.isMaster().ismaster
```
Step 4: Enable certificates in Chrome
`chrome://flags/#allow-insecure-localhost`
### DAO
In the **Data Access Object** (DOA) layer, we can define the function which is directly connected to the database and fetch data and save data from and to the database.
<file_sep>/src/services/v1/users/users.model.ts
import mongoose, { Schema, Document, Types, Model } from "mongoose";
import * as bcrypt from "bcrypt";
import { IPet } from "../pets/pets.model";
export interface IUser extends Document {
email: string;
firstName: string;
lastName: string;
password: string;
permissions: string[];
pets: Types.DocumentArray<IPet>;
comparePassword(password: string): boolean;
}
export interface IUserModel extends Model<IUser> {
hashPassword(password: string): string;
}
export const userSchema: Schema = new Schema(
{
email: {
type: String,
required: true,
unique: true,
lowercase: true
// validate: value => {
// if (!validator.isEmail(value)) {
// throw new Error("Invalid Email address");
// }
// }
},
firstName: { type: String, required: true },
lastName: { type: String, required: true },
password: { type: String, required: true },
pets: { type: Array },
permissions: { type: Array }
},
{ timestamps: true }
);
userSchema.method("comparePassword", function(
candidatePassword: string,
next: any
): void {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) return next(err);
next(null, isMatch);
});
});
userSchema.pre<IUser>("save", function(next) {
const user = this;
if (!user.isModified("password")) return next();
const saltRounds = 10;
bcrypt.hash(user.password, saltRounds, (err, hash) => {
if (err) return next(err);
user.password = hash;
next();
});
});
const User = mongoose.model<IUser, IUserModel>("User", userSchema);
const changeStream = User.watch();
changeStream.on("change", change => {
console.group("Users collection");
console.log(change);
console.groupEnd();
});
export default User;
<file_sep>/ecosystem.config.js
module.exports = {
apps: [
{
name: "Rest API",
script: "./src/server.ts",
interpreter: "tsc",
watch: true,
ignore_watch: ["node_modules"],
exp_backoff_restart_delay: 100,
combine_logs: true,
merge_logs: true,
error_file: "logs/err.log",
out_file: "logs/out.log",
time: true,
env: {
NODE_ENV: "development"
},
env_production: {
NODE_ENV: "production"
}
}
]
};
<file_sep>/src/services/v1/users/users.routes.ts
import express, { Request, Response, NextFunction } from "express";
import { getUsers, getUserById, createUser } from "./users.controller";
import { checkMongoId } from "../../../middlewares/checks.middleware";
const Router = express.Router();
Router.route("/")
.get(async (req: Request, res: Response, next: NextFunction) => {
const users = await getUsers();
res.status(200).json({
payload: users,
status: {
success: true,
code: 200
}
});
})
.post(async (req: Request, res: Response, next: NextFunction) => {
const data = req.body;
const user = await createUser(data);
console.log(user);
if (!user) {
return next({
code: 400,
message: "Incorrect data."
});
}
res.status(200).json({
payload: user,
status: {
success: true,
code: 200
}
});
});
Router.route("/:id").get(
checkMongoId,
async (req: Request, res: Response, next: NextFunction) => {
const user = await getUserById(req.params.id);
if (!user) {
return next({
code: 400,
message: "User is missing"
});
}
res.status(200).json({
payload: user,
status: {
success: true,
code: 200
}
});
}
);
export default Router;
<file_sep>/src/server.ts
import express, { Application } from "express";
import http from "http";
import errorsMiddleware from "./middlewares/errors.middleware";
import commonMiddleware from "./middlewares/common.middleware";
import routesMiddleware from "./middlewares/routes.middleware";
import MongoDB from "./config/database";
MongoDB();
process.on("uncaughtException", e => {
console.log(e);
process.exit(1);
});
process.on("unhandledRejection", e => {
console.log(e);
process.exit(1);
});
const app: Application = express();
commonMiddleware.map(common => common(app));
routesMiddleware.map(routes => routes(app));
errorsMiddleware.map(errors => errors(app));
const { PORT = 3000 } = process.env;
const server = http.createServer(app);
server.listen(PORT, () =>
console.log(`Server is running http://localhost:${PORT}`)
);
| ef0c14376eadb864c2e077dac5e4969ab025d7a4 | [
"YAML",
"Markdown",
"JavaScript",
"Makefile",
"TypeScript",
"Shell"
] | 18 | TypeScript | RomanShabanov/Node-Express-Sockets-MongoDB | e39bd7a7b595cac1d7d7bad66001f8c87c412ced | 5780cd5d4393b1786c8cf92db2155c40eb4d5f4c |
refs/heads/main | <file_sep>Webcam.set({
width:400,
height:400,
image_format:'png',
png_quality: 90
});
camera= document.getElementById("camera");
Webcam.attach("#camera");
function takepic(){
Webcam.snap(function(data_stuff){
document.getElementById("picture").innerHTML="<img id='snapped' src='"+data_stuff+"' >";
});
}
console.log("ml5 version : ", ml5.version);
classifier=ml5.imageClassifier("https://teachablemachine.withgoogle.com/models/FD-XU982-/model.json", imageLoader);
function imageLoader(){
console.log("Model Loaded!");
}
function identify(){
image=document.getElementById("snapped");
classifier.classify(image, getResult);
}
function getResult(error, result){
if(error){
console.error(error);
}
if(result){
console.log(result);
document.getElementById("result_member").innerHTML=result[0].label;
document.getElementById("result_accuracy").innerHTML=result[0].confidence.toFixed(3);
}
} | b621830e76ad2934412b4b3571f8f41978a881e1 | [
"JavaScript"
] | 1 | JavaScript | ELOLOLOHI/FaceRecog-Projects103to105 | 98e394c7f9d9be4260ffaa814f92581cf1bbb96f | 2bac8e67337f8a446a9de53138689943382003eb |
refs/heads/master | <repo_name>nathan-wien/funcalc<file_sep>/src/token.h
#pragma once
#include <climits>
#include <string>
#include <cmath>
struct Token {
enum TokenType {
NIL,
NUMBER,
OPERATOR,
VARIABLE
};
Token() = default;
virtual ~Token() = default;
virtual TokenType GetType() const {
return NIL;
};
};
struct OperatorToken : Token {
TokenType type = OPERATOR;
std::string symbol;
bool is_unary;
OperatorToken() = default;
OperatorToken(std::string symbol) : symbol(symbol), is_unary(false) {}
virtual TokenType GetType() const {
return type;
}
std::string GetSymbol() const {
return symbol;
};
void SetUnary(bool flag) {
is_unary = flag;
}
bool IsUnary() const {
return is_unary;
}
int Precedence() {
if (!is_unary) {
if (symbol == "+" || symbol == "-") {
return 1;
}
if (symbol == "*" || symbol == "/") {
return 2;
}
if (symbol == "^") {
return 3;
}
}
return INT_MAX;
}
bool IsRightAssociative() const {
if (symbol == "^") {
return true;
}
return false;
}
};
struct NumberToken : Token {
TokenType type = NUMBER;
double value;
NumberToken() = default;
NumberToken(double value) : value(value) {}
virtual TokenType GetType() const {
return type;
}
double GetValue() const {
return value;
}
void HandleUnaryOperator(OperatorToken* op_token) {
if (op_token->GetSymbol() == "+") {
value *= 1;
}
else if (op_token->GetSymbol() == "-") {
value *= -1;
}
else if (op_token->GetSymbol() == "sin") {
value = sin(value);
}
else if (op_token->GetSymbol() == "cos") {
value = cos(value);
}
else if (op_token->GetSymbol() == "tan") {
value = tan(value);
}
else if (op_token->GetSymbol() == "cot") {
value = 1 / tan(value);
}
else if (op_token->GetSymbol() == "exp") {
value = exp(value);
}
}
bool IsInteger(double d) {
const double EPS = 1e-6;
double int_part;
double frac_part = std::modf(d, &int_part);
return frac_part < EPS;
}
void HandleBinaryOperator(OperatorToken* op_token, NumberToken* other) {
std::string op_str = op_token->GetSymbol();
if (op_str == "+") {
value += other->value;
}
else if (op_str == "-") {
value -= other->value;
}
else if (op_str == "*") {
value *= other->value;
}
else if (op_str == "/") {
value /= other->value;
}
else if (op_str == "^") {
value = pow(value, other->value);
}
else if (op_str == "div") {
if (!IsInteger(value) || !IsInteger(other->value)) {
std::cout << "Error: cannot apply integer operation on floating point numbers\n";
exit(0);
}
int a = (int) std::round(value);
int b = (int) std::round(other->value);
value = a / b;
}
else if (op_str == "mod") {
if (!IsInteger(value) || !IsInteger(other->value)) {
std::cout << "Error: cannot apply integer operation on floating point numbers\n";
exit(0);
}
int a = (int) std::round(value);
int b = (int) std::round(other->value);
value = a % b;
}
}
};
struct VariableToken : Token {
TokenType type = VARIABLE;
std::string name;
VariableToken() = default;
VariableToken(std::string name) : name(name) {}
virtual TokenType GetType() const {
return type;
}
std::string GetName() const {
return name;
}
};
<file_sep>/lib/dsalib-cpp/structures/tree-set.h
#pragma once
#include <cassert>
#include "avl-tree.h"
#include "array-list.h"
template <typename T>
class TreeSet {
private:
AVLTree<T> tree;
int size;
public:
TreeSet() : size(0) {}
int Size() const {
return size;
}
void Push(T key) {
tree.Push(key);
size++;
}
void Pop(T key) {
assert(tree.Has(key) && "TreeSet::Pop(): invalid key");
tree.Pop(key);
size--;
}
bool Has(T key) const {
return tree.Has(key);
}
T Min() {
return tree.Min();
}
T Max() {
return tree.Max();
}
ArrayList<T> Entries() {
return tree.GetArrayList();
}
~TreeSet() = default;
};
<file_sep>/src/io.h
#pragma once
#include <fstream>
#include <iostream>
#include <limits>
#include "../lib/dsalib-cpp/structures/array-list.h"
#include "console.h"
namespace io {
ArrayList<std::string> ReadConsoleLines() {
console::DrawLine();
std::cout << "Please input the number of lines\n";
std::cout << "=> ";
int num_lines;
while (true) {
std::cin >> num_lines;
if (!std::cin.good()) {
std::cin.clear(); // clear the cin's error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max()); // clear the current line
std::cout << "Error: invalid choice. Please input your choice again\n";
std::cout << "=> ";
}
else break;
}
ArrayList<std::string> lines;
for (int i = 0; i < num_lines; i++) {
std::string line;
std::getline(std::cin, line);
lines.PushBack(line);
}
return lines;
}
ArrayList<std::string> ReadFileLines(std::ifstream& in_file_stream) {
ArrayList<std::string> lines;
std::string line;
while (std::getline(in_file_stream, line)) {
lines.PushBack(line);
}
return lines;
}
ArrayList<std::string> ReadLines() {
std::cout << "Choose how you want to input expressions:\n";
std::cout << "1. Using the console\n";
std::cout << "2. Using text file\n";
std::cout << "=> ";
int choice;
while (true) {
std::cin >> choice;
if (!std::cin.good()) {
std::cin.clear(); // clear the cin's error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max()); // clear the current line
std::cout << "Error: invalid choice. Please input your choice again\n";
std::cout << "=> ";
}
else if (choice != 1 && choice != 2) {
std::cout << "Error: invalid choice. Please input your choice again\n";
std::cout << "=> ";
}
else break;
}
if (choice == 1) {
return ReadConsoleLines();
}
console::DrawLine();
std::cout << "Input the input file (both relative or absolute path can be used)\n";
std::ifstream infile_stream;
while (true) {
std::string file_path;
std::cout << "=> ";
std::cin >> file_path;
infile_stream.open(file_path);
if (!infile_stream.good()) {
std::cout << "Error: could not open file " << file_path << '\n';
infile_stream.close();
}
else break;
}
console::DrawLine();
return ReadFileLines(infile_stream);
}
}
<file_sep>/src/main.cpp
#include <iostream>
#include <string>
#include <iomanip>
#include "../lib/dsalib-cpp/structures/array-list.h"
#include "../lib/dsalib-cpp/structures/queue.h"
#include "../lib/dsalib-cpp/structures/stack.h"
#include "../lib/dsalib-cpp/structures/tree-map.h"
#include "../lib/dsalib-cpp/structures/tree-set.h"
#include "../lib/dsalib-cpp/util/util.h"
#include "io.h"
#include "token.h"
class Calculator {
TreeSet<std::string> operator_set;
ArrayList<std::string> variables;
TreeMap<std::string, double> const_map;
TreeMap<std::string, double> var_map;
void Initialize() {
std::string operators[] = {"+", "-", "*", "/", "^", "div", "mod", "(", ")", "sin", "cos", "tan", "cot", "exp"};
int num_operators = sizeof(operators) / sizeof(*operators);
for (int i = 0; i < num_operators; i++) {
operator_set.Push(operators[i]);
}
KeyValuePair<std::string, double> consts[] = {{"pi", acos(-1)}};
int num_consts = sizeof(consts) / sizeof(*consts);
for (int i = 0; i < num_consts; i++) {
const_map.Push(consts[i].key, consts[i].value);
}
}
bool ValidateEqualSign(std::string line) {
bool has_equal_sign = false;
for (char c : line) {
if (c == '=') {
if (has_equal_sign) return false;
has_equal_sign = true;
}
}
return has_equal_sign;
}
std::string SplitVarName(std::string &line, int line_num) {
int length = line.length();
std::string var_name;
int i;
for (i = 0; i < length; i++) {
if (!util::IsLetter(line[i])) break;
var_name += line[i];
}
if (var_name.length() == 0) {
std::cout << "Error: no variable to assign on line " << line_num << '\n';
exit(0);
}
int equal_sign_pos = -1;
for (; i < length; i++) {
if (line[i] == '=') {
equal_sign_pos = i;
break;
}
}
if (equal_sign_pos == -1) {
std::cout << "Error: no equal sign on line " << line_num << '\n';
}
line = line.substr((uint32_t) (equal_sign_pos + 1), std::string::npos);
return var_name;
}
ArrayList<Token*> Tokenize(std::string& line, int line_num) {
ArrayList<Token*> tokens;
int length = line.length();
for (int i = 0; i < length; i++) {
if (line[i] == ' ') continue;
if (line[i] == '.' || util::IsDigit(line[i])) {
bool has_decimal_point = line[i] == '.';
std::string num_string;
while (i < length) {
if (util::IsDigit(line[i])) {
num_string += line[i];
}
else if (line[i] == '.') {
if (has_decimal_point) {
std::cout << "Error: invalid number on line " << line_num << ", column " << i << '\n';
exit(0);
}
num_string += '.';
}
else {
break;
}
++i;
}
--i;
double num = std::stod(num_string);
tokens.PushBack(new NumberToken(num));
}
else if (util::IsLetter(line[i])) {
std::string word;
while (i < length) {
if (util::IsLetter(line[i])) {
word += line[i];
++i;
}
else break;
}
--i;
if (operator_set.Has(word)) {
tokens.PushBack(new OperatorToken(word));
}
else {
tokens.PushBack(new VariableToken(word));
}
}
else {
std::string symbol;
symbol += line[i];
if (!operator_set.Has(symbol)) {
std::cout << "Error: invalid symbol on line " << line_num << ": " << symbol << '\n';
std::cout << "[" << symbol << "]\n";
exit(0);
}
tokens.PushBack(new OperatorToken(symbol));
}
}
return tokens;
}
void CheckUnaryOperators(ArrayList<Token*>& tokens) {
/**
* Unary Operator Cases:
* 1. first token in the expression
* 2. after opening parenthesis
* 3. after an operator
*/
for (int i = 0; i < tokens.Size(); i++) {
if (tokens[i]->GetType() == Token::OPERATOR) {
auto cur_token = dynamic_cast<OperatorToken*>(tokens[i]);
if (i == 0) {
cur_token->SetUnary(true);
}
else if (tokens[i - 1]->GetType() == Token::OPERATOR) {
auto prev_token = dynamic_cast<OperatorToken*>(tokens[i - 1]);
if (prev_token->symbol != ")") {
cur_token->SetUnary(true);
}
}
}
}
}
void ProcessVariables(ArrayList<Token*>& tokens, int line_num) {
for (int i = 0; i < tokens.Size(); i++) {
if (tokens[i]->GetType() == Token::VARIABLE) {
auto token = dynamic_cast<VariableToken *>(tokens[i]);
std::string name = token->GetName();
double number;
if (const_map.Has(name)) {
number = const_map.Get(name);
}
else {
if (!var_map.Has(name)) {
std::cout << "Error: unassigned variable " + name + " on line " << line_num << '\n';
exit(0);
}
number = var_map.Get(name);
}
delete tokens[i];
tokens[i] = new NumberToken(number);
}
}
}
Queue<Token*> ShuntingYard(ArrayList<Token*>& tokens, int line_num) {
Stack<OperatorToken*> op_stack;
Queue<Token*> postfix_queue;
for (int i = 0; i < tokens.Size(); i++) {
if (tokens[i]->GetType() == Token::NUMBER) {
postfix_queue.Enqueue(tokens[i]);
}
else {
auto op_token = dynamic_cast<OperatorToken*>(tokens[i]);
if (op_token->IsUnary()) {
op_stack.Push(op_token);
}
else if (op_token->GetSymbol() == "(") {
op_stack.Push(op_token);
}
else if (op_token->GetSymbol() == ")") {
while (op_stack.Top()->GetSymbol() != "(") {
postfix_queue.Enqueue(dynamic_cast<Token*>(op_stack.Pop()));
}
op_stack.Pop(); // Pop "("
}
else {
if (!op_stack.Empty() && !op_stack.Top()->IsRightAssociative()) {
while (!op_stack.Empty() && op_stack.Top()->GetSymbol() != "(" && op_stack.Top()->Precedence() >= op_token->Precedence()) {
postfix_queue.Enqueue(dynamic_cast<Token*>(op_stack.Pop()));
}
}
else {
while (!op_stack.Empty() && op_stack.Top()->GetSymbol() != "(" && op_stack.Top()->Precedence() > op_token->Precedence()) {
postfix_queue.Enqueue(dynamic_cast<Token*>(op_stack.Pop()));
}
}
op_stack.Push(op_token);
}
}
}
while (!op_stack.Empty()) {
postfix_queue.Enqueue(op_stack.Pop());
}
return postfix_queue;
}
double Evaluate(Queue<Token*>& postfix_queue, int line_num) {
Stack<Token*> num_stack;
while (!postfix_queue.Empty()) {
if (postfix_queue.Front()->GetType() != Token::OPERATOR) {
num_stack.Push(postfix_queue.Dequeue());
}
else {
auto op_token = dynamic_cast<OperatorToken*>(postfix_queue.Dequeue());
if (op_token->IsUnary()) {
auto num_token = dynamic_cast<NumberToken*>(num_stack.Pop());
num_token->HandleUnaryOperator(op_token);
num_stack.Push(dynamic_cast<Token*>(num_token));
}
else {
auto num_token_b = dynamic_cast<NumberToken*>(num_stack.Pop());
auto num_token_a = dynamic_cast<NumberToken*>(num_stack.Pop());
num_token_a->HandleBinaryOperator(op_token, num_token_b);
num_stack.Push(dynamic_cast<Token*>(num_token_a));
}
}
}
if (num_stack.Size() != 1) {
std::cout << "Error: cannot evaluate expression on line " << line_num << '\n';
exit(0);
}
double result = dynamic_cast<NumberToken*>(num_stack.Pop())->GetValue();
return result;
}
void PrintTokens(ArrayList<Token*>& tokens, int line_num) {
std::cout << "Line " << line_num << ": ";
for (int i = 0; i < tokens.Size(); i++) {
if (tokens[i]->GetType() == Token::NUMBER) {
std::cout << "Number[";
auto token = dynamic_cast<NumberToken*>(tokens[i]);
std::cout << token->GetValue() << "], ";
}
else if (tokens[i]->GetType() == Token::OPERATOR) {
std::cout << "Operator[";
auto token = dynamic_cast<OperatorToken*>(tokens[i]);
std::cout << token->GetSymbol() << "], ";
}
else if (tokens[i]->GetType() == Token::VARIABLE) {
std::cout << "Variable[";
auto token = dynamic_cast<VariableToken*>(tokens[i]);
std::cout << token->GetName() << "], ";
}
}
std::cout << '\n';
}
void ProcessLine(std::string& line, int line_num) {
ArrayList<Token*> tokens = Tokenize(line, line_num);
#ifdef DEBUG
PrintTokens(tokens, line_num);
#endif // DEBUG
CheckUnaryOperators(tokens);
ProcessVariables(tokens, line_num);
Queue<Token*> postfix_queue = ShuntingYard(tokens, line_num);
double result = Evaluate(postfix_queue, line_num);
std::string variable = variables[line_num];
if (var_map.Has(variable)) {
var_map.Pop(variable);
}
var_map.Push(variable, result);
}
public:
void Run() {
Initialize();
ArrayList<std::string> lines = io::ReadLines();
int num_lines = lines.Size();
for (int i = 0; i < num_lines; i++) {
std::cout << lines[i] << '\n';
}
for (int i = 0; i < num_lines; i++) {
if (!ValidateEqualSign(lines[i])) {
std::cout << "Error: Invalid number of equal signs (=) - line " << i << '\n';
std::cout << "Expression: " << lines[i] << '\n';
exit(0);
}
}
for (int i = 0; i < num_lines; i++) {
std::string var_name = SplitVarName(lines[i], i);
variables.PushBack(var_name);
}
for (int i = 0; i < num_lines; i++) {
ProcessLine(lines[i], i);
}
ArrayList<KeyValuePair<std::string, double>> table = var_map.Entries();
console::DrawLine();
std::cout << "Evaluation Result:\n";
for (int i = 0; i < table.Size(); i++) {
KeyValuePair<std::string, double> pair = table[i];
std::string variable = pair.key;
double value = pair.value;
std::cout << std::fixed << std::setprecision(6);
std::cout << '[' << variable << ']' << " = " << value << '\n';
}
}
};
int main() {
Calculator calculator;
calculator.Run();
return 0;
}
<file_sep>/README.md
# Calculator Program
## Introduction
This is a simple console calculator which can calculate multiple expressions at once.
## Implementation
This project does not use any library related to data structures and algorithms. All data structures and algorithms are implemented from scratch.
## Build
This project can be built using CMake and the CMakeLists.txt file. Otherwise, any IDE would be sufficient.
Note: This project was built with the C++14 flag. Enable this flag to avoid compiling errors.
## Usage
The program supports two different modes: input directly in the console, or input with a text file.
Both relative or absolute path can be used for the file mode.
Each line must have the following syntax:
```
<variable> = <expression>
```
Supported operators:
* `+`, `-`, `*`, `/`, `^`
* `div`, `mod` (integers only)
* functions: `sin`, `cos`, `tan`, `cot`, `exp`
`pi` constant is also supported.
Example:
* Input file:
```
a = 2 + 3 + (3)
b = a + 4
c = 3 * b - 3^2
d = c mod 4
e = 10 - 3 * 4
f = 100 - (2 + 3 * 4)
g = (1 + (10 * (3 - 2)))
h = sin(0.5)
i = exp(exp(0.5))
k = pi
x = 2
y = 3
z = x^2 + y^3
```
* Output:
```
Evaluation Result:
[a] = 8.000000
[b] = 12.000000
[c] = 27.000000
[d] = 3.000000
[e] = -2.000000
[f] = 86.000000
[g] = 11.000000
[h] = 0.479426
[i] = 5.200326
[k] = 3.141593
[x] = 2.000000
[y] = 3.000000
[z] = 31.000000
```
<file_sep>/lib/dsalib-cpp/structures/stack.h
#pragma once
#include "singly-linked-list.h"
template <typename Key>
class Stack {
private:
SinglyLinkedList<Key> linked_list;
public:
Stack() = default;
int Size() const {
return linked_list.Size();
}
bool Empty() const {
return linked_list.Size() == 0;
}
void Push(Key key) {
linked_list.PushFront(key);
}
Key Pop() {
assert(linked_list.Size() > 0 && "Stack::Pop(): empty");
return linked_list.PopFront();
}
Key Top() const {
assert(linked_list.Size() > 0 && "Stack::Top(): empty");
return linked_list.Front();
}
friend std::ostream& operator<<(std::ostream& os, const Stack& stack) {
os << "Stack[ " << stack.linked_list << " ]";
return os;
}
~Stack() = default;
};
<file_sep>/lib/dsalib-cpp/structures/key-value-pair.h
#pragma once
template <typename Key, typename Value>
struct KeyValuePair {
Key key;
Value value;
KeyValuePair() = default;
explicit KeyValuePair(Key key) : key(key) {}
KeyValuePair(Key key, Value value) : key(key), value(value) {}
bool operator==(const KeyValuePair& other) {
return key == other.key;
}
bool operator!=(const KeyValuePair& other) {
return key != other.key;
}
bool operator<(const KeyValuePair& other) {
return key < other.key;
}
bool operator>(const KeyValuePair& other) {
return key > other.key;
}
bool operator<=(const KeyValuePair& other) {
return key <= other.key;
}
bool operator>=(const KeyValuePair& other) {
return key >= other.key;
}
bool operator=(const KeyValuePair& other) {
this->key = other.key;
this->value = other.value;
}
friend std::ostream& operator<<(std::ostream& os, const KeyValuePair& pair) {
os << "Pair[ ";
os << "key = " << pair.key << ", ";
os << "value = " << pair.value << " ]";
return os;
}
~KeyValuePair() = default;
};
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(co2003_assignment)
set(CMAKE_CXX_STANDARD 14)
add_executable(
co2003_assignment
src/main.cpp
src/console.h
src/token.h
src/io.h
)
<file_sep>/src/console.h
#pragma once
#include <iostream>
namespace console {
const int LINE_LENGTH = 12;
void DrawLine() {
for (int i = 0; i < LINE_LENGTH; i++) {
std::cout << "_";
}
std::cout << "\n\n";
}
};
<file_sep>/lib/dsalib-cpp/algorithms/search/binary-search.h
#pragma once
namespace binary_search {
template <typename T>
int search(T a[], int begin, int end, T key) {
--end;
int mid = (begin + end) / 2;
while (begin < end && a[mid] != key) {
if (a[mid] < key) {
begin = mid + 1;
} else {
end = mid - 1;
}
mid = (begin + end) / 2;
}
return (a[mid] == key) ? (mid) : (-1);
}
/**
* lower_bound: found the position of the leftmost element that is
* less than or equal to key
*/
template <typename T>
int lower_bound(T a[], int begin, int end, T key) {
while (begin < end) {
int mid = (begin + end) / 2;
if (a[mid] >= key) {
end = mid;
} else {
begin = mid + 1;
}
}
return begin;
}
/**
* upper_bound: found the position of the leftmost element that is
* strictly greater than key
*/
template <typename T>
int upper_bound(T a[], int begin, int end, T key) {
while (begin < end) {
int mid = (begin + end) / 2;
if (a[mid] <= key) {
begin = mid + 1;
} else {
end = mid;
}
}
return begin;
}
}
<file_sep>/lib/dsalib-cpp/structures/queue.h
#pragma once
#include <cassert>
#include "doubly-linked-list.h"
template <typename Key>
class Queue {
private:
DoublyLinkedList<Key> linked_list;
public:
Queue() = default;
int Size() const {
return linked_list.Size();
}
bool Empty() const {
return linked_list.Size() == 0;
}
void Enqueue(Key key) {
linked_list.PushBack(key);
}
Key Dequeue() {
assert(linked_list.Size() > 0 && "Queue::dequeue(): empty");
return linked_list.PopFront();
}
Key Front() const {
assert(linked_list.Size() > 0 && "Queue::getTop(): empty");
return linked_list.Front();
}
friend std::ostream& operator<<(std::ostream& os, const Queue& queue) {
os << "Queue[ " << queue.linked_list << " ]";
return os;
}
~Queue() = default;
}; | ca9296b54f3ce393a53f9e6f229d2e17b6fd79a6 | [
"Markdown",
"CMake",
"C++"
] | 11 | C++ | nathan-wien/funcalc | d8e107c2e253ef0dd56b7e340e8c8dcf1bc93b8b | 6ddcfc23f799c76e7b52a32a19a0349866fcab8d |
refs/heads/master | <repo_name>Jeremiah-Freeman/PHP---Scrabble-Score-Game<file_sep>/README.md
| Behavior | Input | Output |
-----------------------------
| User enters a letter and receives a score for that letter | "K" | 5 |
| User enters a word and receives a score for that word | "LOVE" | 7 |
<file_sep>/tests/ScrabbleScoreTest.php
<?php
require_once "src/ScrabbleScore.php";
class ScrabbleScoreTest extends PHPUnit_Framework_TestCase
{
function test_Add_Singles()
{
//Arrange
$test_ScrabbleScore = new ScrabbleScore;
$input = "k";
//Act
$result = $test_ScrabbleScore->test_Add_Singles($input);
//Assert
$this->assertEquals(5, $result);
}
function test_Whole_Word()
{
//Arrange
$test_ScrabbleScore = new ScrabbleScore;
$input = "love";
//Act
$result = $test_ScrabbleScore->test_Whole_Word($input);
//Assert
$this->assertEquals(7 , $result);
}
function test_Input()
{
//Arrange
$test_ScrabbleScore = new ScrabbleScore;
$input = "hello";
//Act
$result = $test_ScrabbleScore->test_Input($input);
//Assert
$this->assertEquals(8 , $result);
}
}
?>
<file_sep>/src/ScrabbleScore.php
<?php
class ScrabbleScore
{
public $word;
public $score;
function __construct($word, $score)
{
$this->word = $word;
$this->score = $score;
}
public $list_of_letters = array(
'a' => 1,
'e' => 1,
'i' => 1,
'o' => 1,
'u' => 1,
'l' => 1,
'n' => 1,
'r' => 1,
's' => 1,
't' => 1,
'd' => 2,
'g' => 2,
'b' => 3,
'c' => 3,
'm' => 3,
'p' => 3,
'f' => 4,
'h' => 4,
'v' => 4,
'w' => 4,
'y' => 4,
'k' => 5,
'j' => 8,
'x' => 8,
'q' => 10,
'z' => 10
);
function test_Input($input)
{
$output = 0;
$input_letter = str_split($input);
foreach ($input_letter as $letter) {
foreach ($this->list_of_letters as $key => $value) {
if ($letter == $key) {
$output += $value;
}
}
}
return $output;
}
function getLetter()
{
return $this->list_of_letters;
}
function test_Add_Singles($input)
{
$input = array('k' => 5);
return $input['k'];
}
function test_Whole_Word($input)
{
$input = array('l' => 1,'o' => 1,'v' => 4,'e' => 1);
$output = 0;
foreach($input as $value)
{
$output += $value;
}
return $output;
}
}
?>
| 2319a15eadb81c0b96307d2ae797dc48e9f561d2 | [
"Markdown",
"PHP"
] | 3 | Markdown | Jeremiah-Freeman/PHP---Scrabble-Score-Game | 0520416d637ed1178e688d14b58f4df753a0092a | 928d19e073d930ce8855b9873046ca90a51ed0a2 |
refs/heads/master | <file_sep># Project : Jewellery Ecommerce Web Application
## Introduction
Ecommerce web application for a fictional jewellery company called Dream Jewellery.
Initially focusing on customer interaction and functionality to allow customers to browse and search products, add to cart, update cart, go through checkout.
## Technologies
- Database: MySQL
- Backend: Java, Spring Boot, Spring Data JPA
- Frontend: HTML, CSS, Bootstrap, Angular
## Scope of current functionalities
- Choose products by category
- Change display of products
- View single product in more detail
- Add to cart from product list or single product display
- Update cart (increase/decrease quantity, remove from cart)
- View subquantites, subtotals, total quantites and total in cart
- Complete checkout form
## Project status
Ongoing - to complete version one for end of March 2021
## Next steps
- Add cart contents to cache
- Quick view of cart (hover over cart icon)
- Checkout form validation
- Save order to database
- Customer login/logout/signup
<file_sep>package com.jewelleryecommerce.demo.dao;
import com.jewelleryecommerce.demo.entity.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestParam;
@RepositoryRestResource
public interface ProductRepository extends JpaRepository<Product, Long>{
Page<Product> findByCategoryId(@RequestParam("id") Long id, Pageable pageable);
Page<Product> findByDescriptionContaining(@RequestParam("description") String description,
Pageable pageable);
}
<file_sep>package com.jewelleryecommerce.demo.dao;
import com.jewelleryecommerce.demo.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Customer findByEmail(String theEmail);
}
<file_sep>USE `jewellery-ecommerce`;
SET foreign_key_checks = 0;
--
-- Table structure for table `country`
--
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`id` smallint unsigned NOT NULL,
`code` varchar(2) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
--
-- Data for table `country`
--
INSERT INTO `country` VALUES
(1,'ROI','Republic of Ireland'),
(2,'NI','Northern Ireland');
--
-- Table structure for table `county`
--
DROP TABLE IF EXISTS `county`;
CREATE TABLE `county` (
`id` smallint unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`country_id` smallint unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_country` (`country_id`),
CONSTRAINT `fk_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
--
-- Dumping data for table `county`
--
INSERT INTO `county` VALUES
(1,'Carlow',1),
(2,'Cavan',1),
(3,'Clare',1),
(4,'Cork',1),
(5,'Donegal',1),
(6,'Dublin',1),
(7,'Galway',1),
(8,'Kerry',1),
(9,'Kildare',1),
(10,'Kilkenny',1),
(11,'Laois',1),
(12,'Leitrim',1),
(13,'Limerick',1),
(14,'Longford',1),
(15,'Louth',1),
(16,'Mayo',1),
(17,'Meath',1),
(18,'Monaghan',1),
(19,'Offaly',1),
(20,'Roscommon',1),
(21,'Sligo',1),
(22,'Tipperary',1),
(23,'Waterford',1),
(24,'Westmeath',1),
(25,'Wexford',1),
(26,'Wicklow',1),
(27,'Antrim',2),
(28,'Armagh',2),
(29,'Derry',2),
(30,'Down',2),
(31,'Fermanagh',2),
(32,'Tyrone',2);
SET foreign_key_checks = 1; | 3ef4da70aca21853a00250fc60d0a157edf9bf2c | [
"Markdown",
"Java",
"SQL"
] | 4 | Markdown | Aisling-Connaughton/jewellery-ecommerce | d719b1a6f5b5e0f0068afb45d0ef7bf70c2d08ce | 53f8f3b8734bc5a82f4d42e9c868dba7f1d73e04 |
refs/heads/main | <repo_name>JayBee12/ITBadgePDT22021<file_sep>/Teamplate.py
# Calculator Program
# Name:
<file_sep>/Example3for.py
# For loops using the range() function are fairly simple:
# we use a variable to keep an index (a measure of which number we're up to) in this case we use 'i'
# we then use the range() function to create a list of steps to use the index to measure against.
# we can give range 3 numbers: a start number, a stop number, and how many numbers we want to step through:
# NOTE: Unless we tell it to, the computer will start counting at 0 meaning that 10 steps is actually the numbers 0-9
# in this example the range() function is only being provided the stop number, so it assumes we want to start at 0 and finish on the 10th number (9)
for i in range(10):
print(i)
print("\n")
#in this example the range() function starts at 1 and finishes at the 20th number (19) counting every second number
for i in range(1, 20, 2):
print(i)
print("\n")
#What does this loop do?
#for i in range(10, 0, -1):
# print(i)<file_sep>/Example4.py
# We use def to define the structure of a function, functions can be created to expect 'arguments' which are data we provide to the function to do something with
# The examples below are 'pass by value' arguments in that the value is passed to the function rather than a reference or pointer to the variable itself
#This function has no arguments and simply calls the print funtion to print some text to the console
def noArguments():
print("The function with no arguments was called")
#This function takes two variables adds them together and then prints them using the print function
def hasArguments(a, b):
print(a + b)
# This function has a return value meaning that when the function is called it will 'return' whatever is specified, in this case it returns the sum of the
# values of the two variables passed to it
def hasReturns(a, b):
return a + b
#function call
noArguments()
# Function call with arguments
hasArguments(6, 4)
# What do think this function will do
# hasArguments()
# Function wtih return to variable
x = hasReturns(3, 3)
# Print returned data in variable
print(x)
# Print return value directly
print(hasReturns(7, 7))
<file_sep>/Example2elif.py
# Variables
a = 2
b = 3
# Print the variables to make it easier to read
print("a:", a, "b:", b, "\n")
# Below is an example of the "elif" keyword, using elif means that the whole structure is considered: The first conditional statement will that is met will execute
#and the conditional structure will be exited
if a==b:
# If A and B are equal, say so
print("A equals B is TRUE")
elif a!=b:
# If A and B are not equal, say so
print("A equals B is FALSE (A does not Equal B)")
elif a<b:
# If A is less than B, say so
print("A is less than B is TRUE")
elif a<=b:
# If A is less than B or if A is equal to B, say so
print("A is less than or equal to B is TRUE")
elif a>b:
# If A is greater than B, say so
print("A is greater than B is TRUE")
elif a>=b:
# If A is greater than B or if A is equal to B, say so
print("A is greater than or equal to B is TRUE")
else:
print("Not sure how you got here but good job!")<file_sep>/Example3while.py
# While loops run until a certain condition is True or False:
# This loop will never run because 1 will never equal 2
while(1==2):
print("this loop will never run")
# This loop will run forever (or at least until you stop the program or it crashes) because True will never be False
#while(True!=False):
# print("oops")
# This loop will run until the user types the word stop (and only the word stop)
# Note the .lower() function means that any string input will be made lowercase so that it matches what we're expected rgardless of capitalisation
stop = "go"
while(stop.lower() != "stop"):
print("Should I stop?")
stop = input()<file_sep>/Example2if.py
# Variables
a = 2
b = 3
# Print the variables to make it easier to read
print("a:", a, "b:", b, "\n")
# The code below evaluates A and B using various operators:
# == is used to test if the variables have the same value
# != is used to test if the variables DO NOT have the same value
# < is used to test if the variables on the left is less than the one on the right
# <= is used to test if the variables on the left is less than or equal to the one on the right
# > is used to test if the variables on the left is greater than the one on the right
# >= is used to test if the variables on the left is greater than or equal to the one on the right
#
# Once the evaluation has been made it results in either 'True' or 'False'
print(a==b)
print(a!=b, "\n")
# Below is an example of the if statement, in this configuration each 'if' is it's own conditional statement meaning each one that is met will be executed
# even if multiple conditions are met
# If A and B are equal, say so
if a==b:
print("A equals B is TRUE")
# If A and B are not equal, say so
if a!=b:
print("A equals B is FALSE (A does not Equal B)")
# If A is less than B, say so
if a<b:
print("A is less than B is TRUE")
# If A is less than B or if A is equal to B, say so
if a<=b:
print("A is less than or equal to B is TRUE")
# If A is greater than B, say so
if a>b:
print("A is greater than B is TRUE")
# If A is greater than B or if A is equal to B, say so
if a>=b:
print("A is greater than or equal to B is TRUE")<file_sep>/Example1.py
# This is called a comment, it's used to communicate information without the compiler or interpreter thinking that this is code
# The print function is used to output stuff to the console below
# Words you want to print must be in either single or double quote marks - but be consistent
# Use commas to separate different types of output (See below)
print("This is a small program to show variables their types and values\n")
# Declaring & assigning some variables (give them a name & value)
integer = 35
floatingPoint = 2.63
string = "A string of characters"
character = "A"
# Print information about what type the variable is using the type() function as well as the value using the name of the variable
# Also print some plain text to make it more readable
print("The varibale integer is of type", type(integer), "and has the value:", integer)
print("The varibale floatingPoint is of type", type(floatingPoint), "and has the value:", floatingPoint)
print("The varibale string is of type", type(string), "and has the value:", string)
print("The varibale integer is of type", type(character), "and has the value:", character)
| 6c8e2001a42a28c2ba78908fe0885253d08ac991 | [
"Python"
] | 7 | Python | JayBee12/ITBadgePDT22021 | 4f1af478b2270d0bf199995febcb44d46233070b | 82c0c4e62c35d6e1787c4374d4b686a56095ac0b |
refs/heads/master | <file_sep>package com.cognito.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "tasks")
public class OrchestratorTaskController {
}
<file_sep>package com.cognito.common;
import javax.servlet.http.HttpServletRequest;
import com.cognito.exceptions.InvalidRequestException;
import lombok.extern.slf4j.Slf4j;
/**
* Enum class
* @author longphan
*
*/
@Slf4j
public enum Headers {
CLIENT_ID("Client-Id"),
USER_NAME("User-Name"),
USER_POOL_ID("User-Pool-Id"),
REGION("Region"),
AUTHORIZATION("Authorization");
private String value;
Headers(String value) {
this.value = value;
}
/**
* This function determine which header param is missing from the request
* @author longphan
* @param request
* @return
* @throws InvalidRequestException
*/
public static boolean isMissingHeaderParams(HttpServletRequest request) throws InvalidRequestException {
for (Headers header : Headers.values()) {
String headerVal = request.getHeader(header.getValue());
if(headerVal == null || headerVal.isEmpty()){
String msg = "Missing|Empty request header '%s' for method parameter of type String";
log.warn(msg);
throw new InvalidRequestException(String.format(msg, header.getValue()));
}
}
return false;
}
public String getValue() {
return this.value;
}
}
<file_sep>/**
*
*/
package com.cognito.aws;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cognito.aws.model.CognitoUserPool;
import com.cognito.common.TasksConfigContants;
import com.cognito.exceptions.InvalidRequestException;
import lombok.extern.slf4j.Slf4j;
/**
* @author longphan
*
*/
@Component
@Slf4j
public class AwsCognitoJwtAuthentication {
@Autowired
private AwsCognitoRSAKeyProvider cognitoRsaKeyProvider;
/**
* Verify idToken from Cognito user pools
* @author longphan
* @return
* @throws com.cognito.exceptions.InvalidRequestException
*/
public boolean verifyIdToken(@NotNull @Valid CognitoUserPool userPools) throws InvalidRequestException {
try {
cognitoRsaKeyProvider.buildAwsKidStoreUrl(userPools.getRegion(), userPools.getUserPoolId());
Algorithm algorithm = Algorithm.RSA256(cognitoRsaKeyProvider);
JWTVerifier jwtVerifier = JWT.require(algorithm)
.withAudience(userPools.getClientId()) // Validate your apps audience if needed
.build();
DecodedJWT claimsSet = jwtVerifier.verify(userPools.getIdToken());
if(!isIdToken(claimsSet)) {
String msg = "JWT Token doesn't seem to be an ID Token";
log.warn(msg);
throw new InvalidRequestException(msg);
}
if(!claimsSet.getClaim(TasksConfigContants.COGNITO_USERNAME).asString().equals(userPools.getUsername())) {
String msg = "JWT Token doesn't seem to be belong to this user: %s";
log.warn(msg);
throw new InvalidRequestException(String.format(msg, userPools.getUsername()));
}
return true;
} catch (Exception e) {
log.warn(e.getMessage());
throw new InvalidRequestException(e.getMessage());
}
}
/**
* Check the Token which receive from client is Cognito's idToken
* @author longphan
* @param claimsSet
* @return
*/
private boolean isIdToken(DecodedJWT claimsSet) {
return claimsSet.getClaim(TasksConfigContants.COGNITO_TOKEN_USE).asString().equals(TasksConfigContants.ID);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- =========================================================================================================== -->
<!-- Project Details -->
<!-- =========================================================================================================== -->
<groupId>com.avro</groupId>
<artifactId>avro</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- =========================================================================================================== -->
<!-- Project Properties -->
<!-- =========================================================================================================== -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<!-- Library Versions -->
<avro.version>1.8.2</avro.version>
<avro-maven-plugin.version>1.8.2</avro-maven-plugin.version>
<slf4j-api.version>1.7.24</slf4j-api.version>
<!-- Plugin Versions -->
<lombok.version>1.16.18</lombok.version>
<jacoco-maven-plugin.version>0.7.9</jacoco-maven-plugin.version>
<dockerfile-maven-plugin.version>1.3.6</dockerfile-maven-plugin.version>
<!-- Docker Properties -->
<docker.repository.name>203061916556.dkr.ecr.us-east-1.amazonaws.com</docker.repository.name>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-bom</artifactId>
<version>1.11.106</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Framework Libraries -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-avro</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro-ipc</artifactId>
<version>1.8.2</version>
</dependency>
<!-- Amazon API Libraries -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-kinesis</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>net.jpountz.lz4</groupId>
<artifactId>lz4</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Developer Tools -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro-maven-plugin.version}</version>
<configuration>
<stringType>String</stringType>
</configuration>
<executions>
<!-- <execution>
<id>schemas</id>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
<goal>protocol</goal>
<goal>idl-protocol</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory>
</configuration>
</execution> -->
</executions>
</plugin>
<!-- Code Coverage Tools -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco-maven-plugin.version}</version>
<configuration>
<excludes>
<!--<exclude>com/avro/ee/avro/*</exclude>-->
</excludes>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.15.9</version>
<extensions>true</extensions>
<configuration>
<images>
<image>
<name>${docker.repository.name}/${project.name}:${project.version}</name>
<alias>${project.artifactId}</alias>
<build>
<from>${docker.repository.name}/accent-docker-base-java:1.0.0</from>
<tags><!-- define additional tags for the image -->
<tag>latest</tag>
</tags>
<assembly>
<descriptor>assembly.xml</descriptor>
</assembly>
<ports>
<port>8080</port>
</ports>
<cmd>
<shell>
java -jar /maven/${project.artifactId}-${project.version}.jar
</shell>
</cmd>
</build>
</image>
</images>
</configuration>
<executions>
<execution>
<id>build-docker-image</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
<execution>
<id>push-docker-image-to-registry</id>
<phase>deploy</phase>
<goals>
<goal>push</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.avro.aws;
import java.util.LinkedHashMap;
import java.util.List;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class PublisherCrmRequest <PayloadType> {
private List<PayloadType> payload;
private AwsConfig awsConfig;
private String client;
private String crmObjectName;
private LinkedHashMap<String, Object> objectSchema;
}
<file_sep>package com.avro.crm.avro;
import static com.avro.crm.avro.ThrowingConsumer.throwingConsumerWrapper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.SchemaBuilder.BaseFieldTypeBuilder;
import org.apache.avro.SchemaBuilder.FieldAssembler;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericContainer;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class AvroAdapter {
/** Model Mapper Used to Create Avro Based Objects */
private final Mapper mapper;
@Autowired
public AvroAdapter(Mapper mapper) {this.mapper = mapper;}
public <T, AvroType extends GenericContainer> Optional<ByteArrayInputStream> createAvroByteArrayInputStream(
List<T> payload, Class<AvroType> avroClazz) {
if (payload == null || payload.isEmpty()) {
return Optional.empty();
}
List<AvroType> avroPayloadObjects = payload.stream()
.map(record -> mapper.map(record, avroClazz))
.collect(Collectors.toList());
try {
/* Create Byte Array Output Stream */
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
/* Setup Avro Data Writer */
DatumWriter<AvroType> userDatumWriter = new SpecificDatumWriter<>(avroClazz);
DataFileWriter<AvroType> dataFileWriter = new DataFileWriter<>(userDatumWriter);
dataFileWriter.create(avroPayloadObjects.get(0).getSchema(), outputStream);
/* Write Avro File Objects */
avroPayloadObjects.forEach(throwingConsumerWrapper(dataFileWriter::append));
dataFileWriter.close();
return Optional.of(new ByteArrayInputStream(outputStream.toByteArray()));
} catch (IOException e) {
log.warn("Unable to create Avro Byte Array", e);
return Optional.empty();
}
}
/**
* @author longphan
* @param payload
* @param schemaName
* @return Optional<ByteArrayInputStream>
* @throws IOException
*/
public <T> Optional<ByteArrayInputStream> createAvroByteArrayInputStream(LinkedHashMap<String, Object> objectSchema,
List<LinkedHashMap<String, Object>> payload, String schemaName){
//Create Byte Array Output Stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final Schema schema = createSchema(objectSchema, "Crm" + schemaName);
//Mapping data to Record
List<GenericRecord> records = payload.stream().map(item -> buildingData(item, schema)).collect(Collectors.toList());
// Setup Avro Data Writer
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
try (DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<>(datumWriter)) {
/* Write Avro File Objects */
fileWriter.create(schema, outputStream);
records.stream().forEach(throwingConsumerWrapper(fileWriter::append));
}catch(IOException e) {
log.warn("Unable to create Avro Byte Array", e);
return Optional.empty();
}
return Optional.of(new ByteArrayInputStream(outputStream.toByteArray()));
}
/**
* Create Schema
* @param values
* @param schemaName
* @return
*/
private Schema createSchema(LinkedHashMap<String, Object> record, String schemaName) {
return createField(SchemaBuilder.record(schemaName).fields(), record);
}
/**
* Create Schema fields
* @param fields
* @param record
* @return
*/
private Schema createField(FieldAssembler<Schema> fields, LinkedHashMap<String, Object> record) {
record.entrySet().stream()
.forEach(item -> createType(fields.name(item.getKey().toLowerCase()).type().nullable(),
item.getValue().toString()));
return fields.endRecord();
}
/**
* Create field type
* @author longphan
* @param type
* @param field
*/
private void createType(BaseFieldTypeBuilder<Schema> field, String type) {
switch (type) {
case "int":
field.intType().noDefault();
break;
case "boolean":
field.booleanType().noDefault();
break;
/* Return Double Object */
case "double":
case "currency":
case "percent":
field.doubleType().noDefault();
break;
/* Return String Object */
case "id":
case "reference":
case "picklist":
case "multipicklist":
case "combobox":
case "textarea":
case "phone":
case "url":
case "date":
case "datetime":
case "email":
case "anytype":
case "string":
field.stringType().noDefault();
break;
/* Return Object which is not reading */
case "_":
log.warn("Unknown Data Type: {}", type);
break;
case "address":
case "encryptedstring":
log.warn("Unknown Data Type: {}", type);
break;
default:
break;
}
}
/**
* mapping data to Generic record
* @param dimension
* @param outputSchema
* @return
*/
private GenericRecord buildingData(LinkedHashMap<String, Object> data, Schema schema) {
GenericRecord record = new GenericData.Record(schema);
data.entrySet().stream().filter(f -> schema.getField(f.getKey().toLowerCase()) != null)
.forEach(item -> record.put(item.getKey().toLowerCase(), item.getValue()));
return record;
}
}
<file_sep>#!/usr/bin/env bash
remove_snapshot()
{
echo "Remove SNAPSHOT started"
mvn versions:set -DremoveSnapshot
VERSIONSTATUS=$?
if [ $VERSIONSTATUS -eq 0 ]; then
echo "Remove SNAPSHOT Successful"
build_project
else
echo "Remove SNAPSHOT Failed"
fi
}
build_project()
{
echo "Build started"
mvn clean deploy
BUILDSTATUS=$?
if [ $BUILDSTATUS -eq 0 ]; then
echo "Build Successful"
revert_snapshot
else
echo "Build Failed"
revert_snapshot
fi
}
revert_snapshot()
{
echo "Revert Started"
mvn versions:revert
REVERTSTATUS=$?
if [ $REVERTSTATUS -eq 0 ]; then
echo "Revert Successful"
else
echo "Revert Failed"
fi
}
###
# Main body of script starts here
###
echo "Start of script..."
remove_snapshot
echo "End of script..."<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>aws.cognito</groupId>
<artifactId>cognito</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!-- =========================================================================================================== -->
<!-- Parent Project Details -->
<!-- =========================================================================================================== -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<!-- Docker Properties -->
<docker.repository.name>203061916556.dkr.ecr.us-east-1.amazonaws.com</docker.repository.name>
</properties>
<dependencies>
<!-- Spring Framework Libraries -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Serilization Libraries -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.4</version>
</dependency>
<!-- Developer Tools -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.272</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Code Coverage Tools -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<configuration>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.15.9</version>
<extensions>true</extensions>
<configuration>
<images>
<image>
<name>${docker.repository.name}/${project.name}:${project.version}</name>
<alias>${project.artifactId}</alias>
<build>
<from>${docker.repository.name}/accent-docker-base-java:1.0.0</from>
<tags><!-- define additional tags for the image -->
<tag>latest</tag>
</tags>
<assembly>
<descriptor>assembly.xml</descriptor>
</assembly>
<ports>
<port>8080</port>
</ports>
<cmd>
<shell>
java -jar /maven/${project.artifactId}-${project.version}.jar
</shell>
</cmd>
</build>
</image>
</images>
</configuration>
<executions>
<execution>
<id>build-docker-image</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
<execution>
<id>push-docker-image-to-registry</id>
<phase>deploy</phase>
<goals>
<goal>push</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Used by build.sh to strip SNAPSHOT version for production builds -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.avro;
import java.util.Arrays;
import org.dozer.DozerBeanMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
public class ExchangeDatapublisherApplication {
public static void main(String[] args) {
SpringApplication.run(ExchangeDatapublisherApplication.class, args);
}
@Bean(name = "org.dozer.Mapper")
public DozerBeanMapper dozerBean() {
DozerBeanMapper dozerBean = new DozerBeanMapper();
dozerBean.setMappingFiles(Arrays.asList(
"dozer-account-mappings.xml",
"dozer-contact-mappings.xml",
"dozer-opportunity-mappings.xml",
"dozer-event-mappings.xml",
"dozer-lead-mappings.xml",
"dozer-task-mappings.xml",
"dozer-user-mappings.xml"));
return dozerBean;
}
} | 63748fe7a67f3603f081fe279cc68776d08f947c | [
"Java",
"Maven POM",
"Shell"
] | 9 | Java | LoganPhan/AWS | 245df13c0b1e75917c53119420e36d01a093d0e8 | 2c056c5c08a97476f0c22d533980efd373a0dac4 |
refs/heads/master | <file_sep><?php
$conn = mysqli_connect("localhost", "root", "<PASSWORD>", "freelancer");
$title = $_POST['title'];
$token = $_POST['token'];
$description = $_POST['description'];
$result = $conn->query("INSERT INTO videos (token, description, title) VALUES ('$token','$description','$title')");
if($result){
header("Location: ../histories.php");
};
?><file_sep><?php include "./templates/header.php";?>
<?php if(isset($_GET["status"])) { ?>
<?php if($_GET["status"] == "ok") { ?>
<section>
<div class="justify-content-center">
<div class="ml-lg-5 ml-3 mb-5 col-lg-5 col-11 alert alert-success alert-dismissible fade show fixed-bottom"
role="alert">
<strong>Gracias por contactarme!</strong> He recibido tu mensaje.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</section>
<?php } else { ?>
<section>
<div class="justify-content-center">
<div class="ml-lg-5 ml-3 mb-5 col-lg-5 col-11 alert alert-danger alert-dismissible fade show fixed-bottom"
role="alert">
<strong>Ocurrio un problema!</strong> Tu mensaje no ha sido enviado.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</section>
<?php } ?>
<?php } ?>
<section id="banner">
<div class="pos-f-t">
<!-- <div class="collapse" id="navbarToggleExternalContent">
<div class="bg-blue p-4">
<h5 class="text-white h4">a<NAME></h5>
<span class="text-white">Toggleable via the navbar brand.</span>
</div>
</div> -->
<nav class="navbar navbar-dark bg-blue fixed-top shadow">
<img src="./assets/images/logo_jara.png" alt="">
<!-- <button type="button" class="btn btn-light">
<b>
!Mis historias¡
</b>
</button> -->
<ul class="mt-3">
<a href="https://www.instagram.com/andresjaramilloalvarez/" style="color: black"><i
class="fab fa-instagram fa-2x"></i></a>
<a href="https://www.facebook.com/andres.j.alvarez.12" style="color: black"><i
class="fab fa-facebook fa-2x"></i></a>
<a href="https://www.youtube.com/channel/UCarmY6MEfYp31eTZPBcp2jg" style="color: black"><i
class="fab fa-youtube fa-2x"></i></a>
</ul>
</nav>
</div>
</section>
<section id="intro">
<div class="bg-blue container-fluid">
<div class="row mx-2" style="padding-top: 100px; padding-bottom: 50px">
<div class="col-xl-6 mb-3 mx-3">
<h1>Encuentra tu fórmula de la Felicidad y la Productividad</h1>
<!-- <h4 class="mt-2">Transforma tu vida, dirige tu camino</h4> -->
<center>
<button data-toggle="modal" data-target="#contactame" type="button" style="border-radius: 30px"
class="btn btn-lg btn-dark mt-2 rounded-pill">¡¡Contáctame!!</button>
</center>
<h5 class="mt-4" style="font-family: 'Coming Soon', cursive">Si quieres Mejorar La Felicidad o
Productividad de Tu
Vida o Tu Empresa</h5>
</div>
<!-- <div class="col-xl-5 d-none d-lg-block mb-1 mx-3 embed-responsive embed-responsive-16by9"
style="border-radius: 20px">
<iframe width="480" height="270" src="https://www.powtoon.com/embed/e0FPOMhoNse/"
frameborder="0"></iframe>
</div> -->
<img class="col-xl-4 d-none d-lg-block rounded-circle" src="./assets/images/andres-banner-3.png"
alt="Andrés" title="Andrés" height="400px" width="400px" />
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="contactame" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-blue">
<h5 class="modal-title" id="exampleModalLabel">Nuevo Mensaje</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="./services/email.php">
<div class="form-group">
<label for="email" class="col-form-label">Correo:</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<div class="row">
<div class="col-6 form-group">
<label for="name" class="col-form-label">Nombre:</label>
<input name="name" type="text" class="form-control" id="name" required>
</div>
<div class="col-6 form-group">
<label for="telfono" class="col-form-label">Teléfono:</label>
<input name="telefono" type="number" class="form-control" id="telefono">
</div>
</div>
<label for="message" class="col-form-label">Mensaje:</label>
<div class="form-group">
<textarea name="mensaje" class="form-control" id="message" required></textarea>
</div>
<div class="d-flex justify justify-content-center">
<button type="submit" class="btn btn-warning">Enviar</button>
<button type="button" class="btn btn-outline-secondary ml-1"
data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<section>
<div class="container-fluid">
<!-- <div class="row my-5 mx-6">
<div class="col-lg-8">
<h1>Te ayudare a crear un vida más organizada</h1>
</div>
</div> -->
<div class="row mt-4 mx-6">
<div class="col-lg-6">
<img src="./assets/images/andres-one.png" class="img-fluid">
</div>
<div class="col-lg-6">
<h2>Tipping Points</h2>
<p>Mi Formula de la Felicidad y La Productividad es una charla que invita a la reflexión a través de un
recorrido por el tiempo en el que los participantes descubren sus Tipping Points
</p>
</div>
</div>
<div class="row mt-4 mx-6">
<div class="col-lg-6 d-lg-none mb-1 mx-3 embed-responsive embed-responsive-16by9"
style="border-radius: 20px">
<iframe width="480" height="270" src="https://www.powtoon.com/embed/f6cFluO2cNT/
" frameborder="0"></iframe>
<!-- https://www.powtoon.com/embed/e0FPOMhoNse/ -->
<!-- <img src="./assets/images/andres-two.png" class="img-fluid"> -->
</div>
<div class="col-lg-6">
<h2></h2>
<p>Tipping Points o Puntos de Quiebre, que no son otra cosa, que los momentos de cambio en la vida, esos
sucesos que construyen a los seres humanos y a los que definitivamente les debemos gratitud.
</p>
</div>
<div class="col-lg-6 d-none d-lg-block embed-responsive"
style="border-radius: 20px;height: 310px;margin-top: inherit;">
<iframe width="480" height="270" src="https://www.powtoon.com/embed/e0FPOMhoNse/"
frameborder="0"></iframe>
<!-- <img src="./assets/images/andres-two.png" class="img-fluid"> -->
</div>
</div>
<div class="row mt-4 mx-6">
<div class="col-lg-6">
<img src="./assets/images/andres-four.png" class="img-fluid">
</div>
<div class="col-lg-6">
<h2>Comó solucionar un problema?</h2>
<p>Todo en esta vida es una cuestión de actitud. Ver el vaso medio lleno o medio vacío depende
únicamente de TI. Para ser feliz siempre debes verlo medio lleno, no dejes que tus preocupaciones o
tus pensamientos pesimistas te afecten
</p>
</div>
</div>
</div>
</section>
<section>
<div class="container-fluid pb-4 bg-blue">
<div class="row my-5 mx-6">
<div class="col-lg-8">
<h1>¿ El café te hace feliz ?</h1>
</div>
</div>
<div class="row mt-4 mx-4">
<div class="col-lg-6 mb-3">
<img src="./assets/images/andres_cata_cafe.png" class="img-fluid">
</div>
<div class="col-lg-6">
<h2>Porqué el café nos hace felices</h2>
<br>
<p class="text-minor">El consumo del café ayuda a prevenir los problemas emocionales ya que estimula la
producción de
serotonina y dopa mina consideradas como las hormonas de la felicidad. El café tiene la capacidad de
proporcionarnos sensación de bienestar, las personas que consumimos de dos a cuatro tazas al día
tenemos una vida más positiva porque la cafeína puede acceder a casi todos los sistemas de
recompensa reconocidos para el cerebro, esta bebida genera placer en todo nuestro cuerpo reduce la
incidencia de los pensamientos negativos y nos ayuda a estar más felices y contentos. Por eso
podemos decir que el café nos hace felices
</p>
</div>
</div>
</div>
</section>
<section>
<div class="container-fluid bg-white">
<div class="row my-5 mx-6">
<div class="col-12 text-center">
<h1>Empresas que te ayudan a ser mas feliz y productivo</h1>
</div>
</div>
<div class="row mt-5 mx-6">
<div class="col-12 col-lg-4">
<div class="card mt-2">
<img src="./assets/images/bolicheria.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h4 class="card-title">Bolicheria</h4>
<p class="card-text">Para ser Feliz y Productivo debes tener un equilibrio en Tu vida. No todo
puede ser trabajo y por eso decidimos crear en el año 2010 un centro de diversiones para
compartir con la familia y amigos.
Aquí tendrás una experiencia inolvidable</p>
</div>
</div>
</div>
<div class="col-12 col-lg-4">
<div class="card card-hp mt-2">
<img src="./assets/images/green.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h4 class="card-title">Green</h4>
<p class="card-text">
Muchos estudios han demostrado que la alimentación y las emociones están directamente
relacionados, dependiendo de como te sientas, comes de una manera u otra, y depende de lo
que comas puedes mejorar o empeorar tu estado emocional.</p>
</div>
</div>
</div>
<div class="col-12 col-lg-4">
<div class="card mt-2">
<img src="./assets/images/logo-crea.png" class="card-img-top" alt="...">
<div class="card-body">
<h4 class="card-title">Crea</h4>
<p class="card-text text-left">CREA Consultores es una Startup pereirana fundada en el año
2018, y
especializada en desarrollar modelos comerciales y de servicio al cliente, articulando el
escenario digital para fortalecer las experiencias de cada marca.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="media">
<div class="container mt-3 position-abso bg-white">
<div class="row" id="media-deploy">
<?php ?>
</div>
</div>
</section>
<section>
<footer class="container-fluid bg-blue">
<nav class="navbar navbar-dark bg-blue shadow justify-content-center">
<!-- <img src="./assets/images/logo_jara.png" alt=""> -->
<!-- <button type="button" class="btn btn-dark">
<b>
!Mis historias¡
</b>
</button> -->
<span>Copyirght© <NAME> 2019</span>
<!-- <ul class="mt-3">
<a href="https://www.instagram.com/andresjaramilloalvarez/" style="color: black"><i
class="fab fa-instagram fa-2x"></i></a>
<a href="https://www.instagram.com/andresjaramilloalvarez/" style="color: black"><i
class="fab fa-facebook fa-2x"></i></a>
<a href="https://www.instagram.com/andresjaramilloalvarez/" style="color: black"><i
class="fab fa-twitter fa-2x"></i></a>
</ul> -->
</nav>
</footer>
</section>
<?php include "./templates/footer.php";?><file_sep><?php
$conn = mysqli_connect("localhost", "root", "<PASSWORD>", "freelancer");
$reponse = [];
$result = $conn->query("SELECT token, description, title FROM videos");
while($row = $result->fetch_array(MYSQLI_ASSOC))
$response[] = $row;
echo json_encode($response);
?><file_sep><?php
$conn = mysqli_connect("localhost", "root", "1234", "freelancer");
?><file_sep><?php include "./config_db.php";?>
<!-- Query -->
<?php
$reponse = [];
$result = $conn->query("SELECT token, description, title FROM videos");
while($row = $result->fetch_array(MYSQLI_ASSOC))
$response[] = $row;
?>
<?php include "./templates/header.php";?>
<section id="banner">
<div class="pos-f-t">
<div class="collapse" id="navbarToggleExternalContent">
<div class="bg-warning p-4">
<h5 class="text-white h4"><NAME></h5>
<span class="text-white">Toggleable via the navbar brand.</span>
</div>
</div>
<nav class="navbar navbar-dark bg-warning fixed-top">
<button type="button" class="btn btn-light rounded-pill">
<b>
!Mis historias¡
</b>
</button>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
</div>
</section>
<!-- <section id="intro">
<div class="bg-light">
<div class="container">
<div id="scene">
<div data-depth="1.00">
<img src="./assets/images/andres-person.png" />
</div>
<div data-depth="1.00"><img src="./pages/images/layer1.png" /></div>
<div data-depth="0.80"><img src="./pages/images/layer2.png" /></div>
<div data-depth="0.60"><img src="./pages/images/layer3.png" /></div>
<div data-depth="0.40"><img src="./pages/images/layer4.png" /></div>
<div data-depth="0.20"><img src="./pages/images/layer5.png" /></div>
<div data-depth="0.00"><img src="./pages/images/layer6.png" /></div>
</div>
</div>
</div>
</section> -->
<section id="media" style="margin-top: 80px;">
<div class="row mx-1 mt-2 d-flex justify-content-center" id="media-deploy">
<?php foreach( $response as $arr => $values) { ?>
<div class="col-12 col-md-6 col-lg-4">
<div class="card bg-light mb-3">
<div class="rounded-top embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item"
src="https://www.youtube.com/embed/<?php echo $values['token']?>" allowfullscreen></iframe>
</div>
<div class="card-body">
<h5><?php echo $values['title']?></h5>
<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover"
data-placement="bottom" data-content="<?php echo $values['description']?>">
Descripción
</button>
</div>
</div>
</div>
<?php } ?>
</div>
</section>
<?php include "./templates/footer.php";?><file_sep><?php
$email = isset($_POST["email"]) ? $_POST["email"] : " ";
$name = isset($_POST["name"]) ? $_POST["name"] : " ";
$message = isset($_POST["mensaje"]) ? $_POST["mensaje"] : " ";
$telefono = isset($_POST["telefono"]) ? $_POST["telefono"] : " ";
$mensaje = "Contacto: ".$email."\nNombre:".$name."\nMensaje: ".$message."\nTeléfono:".$telefono."\n";
if(mail("<EMAIL>", "Contacto", $mensaje)){
if(isset($_POST["email"])){
$correo = "Hola $name\nMuchas gracias por escribirnos.\nNos encanta saber que estas comprometido con tener una vida más feliz y productiva.\n\nSoy <NAME> una persona como Tu, llena de sueños, con una linda familia conformada de tres Hijos, Santiago y los Mellizos Alicia y <NAME>, una hermosa esposa Catalina y toda una vida llena de milagros, Tipping points, historias y aprendizajes por lo que le agradezco cada segundo a Dios.\n\nPronto me comunicare contigo, para que juntos descubramos tus milagros y agradezcamos por ellos.\n\nSer Feliz y Productivo solo depende de Ti y lo mejor de todo es Gratis.\n\nUn abrazo\n\nJara";
mail($email,"<NAME>",$correo);
}
header('Location: ../index.php?status=ok');
}
else
header('Location: ../index.php?status=fail');
?><file_sep><?php include "./templates/header.php" ?>
<section class="d-flex justify-content-center">
<form class="container m-5 col-8 rounded shadow bg-white" style="height: 800px">
<div class="container my-5 d-flex flex-column justify-content-center">
<h5>Pregunta aquí?</h5>
<figure class="figure">
<center>
<img src="./assets/emojis/theme-two/5.png" id="emoji" width="40px" height="30px"
class="figure-img img-fluid rounded emoji" alt="...">
</center>
</figure>
<input type="range" class="input-emoji custom-range" step="1.0" min="0" max="10" id="range-emoji">
</div>
<div class="container my-5 d-flex flex-column justify-content-center">
<h5>Pregunta aquí?</h5>
<textarea class="form-control mt-4" name="description"></textarea>
</div>
</form>
</section>
<?php include "./templates/footer.php" ?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <meta http-equiv="X-UA-Compatible" content="ie=edge" /> -->
<title>Andres</title>
<!-- Bootstrap styles -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="<KEY>" crossorigin="anonymous" />
<link rel="stylesheet" href="./src/css/manage.css" />
</head>
<body id="cnt" class="bg-light">
<div class="container">
<section id="banner-section" class="border-down">
<div class="row">
<div class="col-1 m-3">
<i class="fas fa-angry"></i>
</div>
</div>
</section>
</div>
<div class="container">
<section id="manage-section">
<div class="row">
<div class="col-5 col-md-3 px-0 border-right">
<ul class="nav flex-column">
<li id="videos" class="nav-item option-menu activate">
<a class="nav-link black">Videos</a>
</li>
<li id="encuestas" class="nav-item option-menu">
<a class="nav-link black">Encuestas</a>
</li>
<li id="analisis" class="nav-item option-menu">
<a class="nav-link black">Análisis</a>
</li>
<li id="analisis" class="nav-item option-menu">
<a class="nav-link black">Mensajes</a>
</li>
</ul>
</div>
<div id="render" class="col-7 col-md-9">
<div id="content" class="row">
<form class="col-12" action="./services/save_video.php" method="POST">
<div class="form-row">
<div class="col-md-6 mb-3">
<label>Título</label>
<input type="text" class="form-control" name="title" placeholder="Título"
required />
<div class="valid-feedback"></div>
</div>
<div class="col-md-6 mb-3">
<label>Código</label>
<input type="text" class="form-control" name="token" placeholder="Código"
required />
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="validationServer02">Descripción</label>
<textarea class="form-control" name="description">
</textarea>
</div>
</div>
<button class="btn btn-primary" type="submit">Añadir</button>
</form>
</div>
</div>
</div>
</section>
</div>
<?php include "./templates/footer.php"; ?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Andres</title>
<!-- Bootstrap styles -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="<KEY>"
crossorigin="anonymous"
/>
</head>
<body class="bg-dark">
<section id="login-section">
<div class="row">
<div class="col-4"></div>
<div class="col-4 border border-secondary rounded mt-5 bg-white">
<form class="m-3" action="./validate.php" method="POST">
<div class="form-group ">
<label for="exampleInputEmail1">User</label>
<input
type="text"
name="nickname"
class="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="Enter email"
/>
<?php if (isset($_GET['error'])) { ?>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<?php } ?>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input
type="<PASSWORD>"
name="password"
class="form-control"
id="exampleInputPassword1"
placeholder="<PASSWORD>"
/>
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</div>
</section>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script src="../src/js/jquery-3.2.1.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
</html>
<file_sep><?php
$conn = mysqli_connect("localhost", "root", "<PASSWORD>", "freelancer");
session_start();
$nickname = $_POST['nickname'];
$password = $_POST['password'];
$result = $conn->query("SELECT * FROM users WHERE nickname = '$nickname' AND password = '$<PASSWORD>'");
$user = $result->fetch_array(MYSQLI_ASSOC);
if ($user) {
header('Location: ../manage.html');
} else {
header('Location: login.php?error=1');
}
?><file_sep>const values = {
urlApi: "http://localhost/freelancer/happy-project/services/"
};
| 2fd0e2d88849a87896af6d95d1c1fcd89d94fef7 | [
"JavaScript",
"PHP"
] | 11 | PHP | scam627/happy-project | f001ed7221eb64a0bf8f3129f3f462725f881547 | cc091229356fe789813528e2f52b5b844e9d9c54 |
refs/heads/master | <repo_name>Ivan1998popov/WS_Home_work6<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/ui/fragments/MovieItemFragment.java
package ru.myproject.ws_home_work6.ui.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import ru.myproject.ws_home_work6.R;
import ru.myproject.ws_home_work6.model.Movie;
import ru.myproject.ws_home_work6.ui.presenter.MovieListPresenter;
public class MovieItemFragment extends Fragment implements MovieListPresenter.ViewMovie {
private ImageView image;
private TextView title;
private TextView plot;
private TextView year;
private TextView rate;
private TextView awards;
private TextView actors;
private TextView website;
private MovieListPresenter presenter;
private ImageView editMovie, deleteMovie;
Movie mMovie;
Bundle bundle;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_description_item, container,
false);
image = v.findViewById(R.id.image_poster_movie);
title = v.findViewById(R.id.title);
plot = v.findViewById(R.id.text_description_movie);
year = v.findViewById(R.id.year);
rate = v.findViewById(R.id.text_rating);
awards = v.findViewById(R.id.text_award);
actors = v.findViewById(R.id.text_actors);
website = v.findViewById(R.id.text_website);
editMovie = v.findViewById(R.id.edit_movie);
deleteMovie = v.findViewById(R.id.btn_delete_movie);
bundle = getArguments();
editMovie.setOnClickListener(v1 -> {
EditAddMovieFragment editAddMovieFragment = EditAddMovieFragment.newInstance(mMovie);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, editAddMovieFragment)
.addToBackStack(null)
.commit();
});
deleteMovie.setOnClickListener(v1 -> {
presenter.deleteMovie(mMovie.getId());
MovieListFragment movieListFragment = new MovieListFragment();
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, movieListFragment)
.commit();
});
return v;
}
public static MovieItemFragment newInstance(int id) {
MovieItemFragment fragment = new MovieItemFragment();
Bundle args = new Bundle();
args.putInt("id", id);
fragment.setArguments(args);
return fragment;
}
@Override
public void onStart() {
super.onStart();
bundle = getArguments();
if (bundle != null) {
presenter.loadItemMovieList(bundle.getInt("id"));
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
presenter = new MovieListPresenterImpl(this);
}
@Override
public void addLoadedMovie(Movie movie) {
title.setText(movie.getTitle());
plot.setText(movie.getPlot());
year.setText(String.valueOf(movie.getYear()));
rate.setText(String.valueOf(movie.getRate()));
awards.setText(movie.getAwards());
actors.setText(movie.getActors());
website.setText(movie.getWebsite());
image.setImageDrawable(image.getContext().getDrawable(
image.getContext().getResources().getIdentifier(
movie.getPoster(), "drawable", image.getContext().getPackageName())));
mMovie = movie;
}
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/model/Movie.java
package ru.myproject.ws_home_work6.model;
import com.google.gson.annotations.JsonAdapter;
import java.io.Serializable;
public class Movie implements Serializable {
private String title;
private int year;
private Double rate;
private String plot;
private String awards;
private String actors;
private String website;
private String poster;
private Integer id;
public Movie(){
}
public int getId() {
return id;
}
public void setId(Integer id) {
this.id=id;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getAwards() {
return awards;
}
public void setAwards(String awards) {
this.awards = awards;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
public String getPlot() {
return plot;
}
public void setPlot(String plot) {
this.plot = plot;
}
// public static Comparator<Movie> sMovieComparator = new Comparator<Movie>() {
//
// @Override
// public int compare(Movie o1, Movie o2) {
//
// Float rating_movie1 = o1.getRate();
// Float rating_movie2 = o2.getRate();
//
//
// return rating_movie2.compareTo(rating_movie1);
// }
// };
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/network/service/MovieService.java
package ru.myproject.ws_home_work6.network.service;
import java.util.ArrayList;
import io.reactivex.Single;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import ru.myproject.ws_home_work6.model.Movie;
public interface MovieService {
@GET("/api/movies/fetchMovies?sort=desc")
Single<Response<ArrayList<Movie>>> fetchMovies();
@GET("/api/movies/fetchMovie/{movieId}")
Single<Response<Movie>> fetchMovie(@Path("movieId") int id);
@PUT("/api/movies/updateMovie")
Single<Response<Movie>> updateMovie(@Body Movie movie);
@POST("/api/movies/createMovie")
Single<Response<Movie>> createMovie(@Body Movie movie);
@DELETE("/api/movies/deleteMovie/{movieId}")
Single<Response<Boolean>> deleteMovie(@Path("movieId") int id);
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/network/service/AuthService.java
package ru.myproject.ws_home_work6.network.service;
import android.os.AsyncTask;
import io.reactivex.Single;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Header;
import retrofit2.http.POST;
import ru.myproject.ws_home_work6.model.Registration;
import ru.myproject.ws_home_work6.model.StatusRegistration;
import ru.myproject.ws_home_work6.model.TokenResponse;
public interface AuthService {
String AUTHORIZATION_HEADER="Authorization";
String TOKEN_PREFIX="Bearer ";
String TOKEN_PREFIX_BASIC="Basic ";
@FormUrlEncoded
@POST("oauth/token")
Single<Response<TokenResponse>> singInByPassword(@Header("Authorization") String header,
@Field("username") String username,
@Field("password") String password,
@Field("grant_type") String grantType);
@POST("auth/register")
Single<Response<StatusRegistration>> registerIn(@Body Registration registration);
Call<TokenResponse> refreshToken(@Field("refresh_token") String refreshToken,
@Field("grant_type") String grantType);
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/utils/MyApplication.java
package ru.myproject.ws_home_work6.utils;
import android.app.Application;
import android.content.Intent;
import ru.myproject.ws_home_work6.model.TokenResponse;
import ru.myproject.ws_home_work6.network.RestApi;
import ru.myproject.ws_home_work6.network.service.AuthService;
import ru.myproject.ws_home_work6.ui.activities.LoginActivity;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Prefs.init(this);
RestApi.init((route, response) -> {
String refreshToken=Prefs.get().getString(Prefs.Keys.RefreshToken.toString(),
null);
if(refreshToken!=null){
LoginController.getOwrInstance().setAccessToken(null);
TokenResponse tokenResponse =RestApi.createService(AuthService.class)
.refreshToken(refreshToken,"refresh_token")
.execute().body();
if(tokenResponse!=null){
LoginController.getOwrInstance().setAccessToken(tokenResponse.getAccessToken());
LoginController.getOwrInstance().setRefreshToken(tokenResponse.getRefreshToken());
return response.request().newBuilder()
.addHeader(AuthService.AUTHORIZATION_HEADER,
AuthService.TOKEN_PREFIX+
tokenResponse.getAccessToken()).build();
}else {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}else{
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
return null;
});
}
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/ui/activities/InfoActivity.java
package ru.myproject.ws_home_work6.ui.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import ru.myproject.ws_home_work6.R;
import ru.myproject.ws_home_work6.model.Movie;
import ru.myproject.ws_home_work6.ui.fragments.MovieListFragment;
import ru.myproject.ws_home_work6.utils.LoginController;
public class InfoActivity extends AppCompatActivity implements MovieListFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
MovieListFragment movieListFragment =
MovieListFragment.newInstance(LoginController.getOwrInstance().getLogin());
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, movieListFragment)
.commit();
}
@Override
public void toastMovieTitle(Movie movie) {
}
}
<file_sep>/app/src/main/java/ru/myproject/ws_home_work6/ui/fragments/MovieListPresenterImpl.java
package ru.myproject.ws_home_work6.ui.fragments;
import android.util.Log;
import java.util.ArrayList;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import ru.myproject.ws_home_work6.model.Movie;
import ru.myproject.ws_home_work6.network.RestApi;
import ru.myproject.ws_home_work6.network.SingleResponseFlatMap;
import ru.myproject.ws_home_work6.network.service.MovieService;
import ru.myproject.ws_home_work6.ui.presenter.MovieListPresenter;
class MovieListPresenterImpl implements MovieListPresenter {
private View view;
private ViewMovie mViewMovie;
private MovieService mMovieService;
public MovieListPresenterImpl(MovieListPresenter.View view){
this.view =view;
mMovieService= RestApi.createService(MovieService.class);
}
public MovieListPresenterImpl(){
mMovieService= RestApi.createService(MovieService.class);
}
public MovieListPresenterImpl(MovieListPresenter.ViewMovie viewMovie) {
this.mViewMovie=viewMovie;
mMovieService=RestApi.createService(MovieService.class);
}
@Override
public void loadItemMovieList(Integer id) {
mMovieService.fetchMovie(id)
.subscribeOn(Schedulers.io())
.flatMap(new SingleResponseFlatMap<>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Movie>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Movie movie) {
mViewMovie.addLoadedMovie(movie);
}
@Override
public void onError(Throwable e) {
}
});
}
@Override
public void loadMovieList() {
mMovieService.fetchMovies()
.subscribeOn(Schedulers.io())
.flatMap( new SingleResponseFlatMap<>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<ArrayList<Movie>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(ArrayList<Movie> movies) {
view.addLoadedItems(movies);
}
@Override
public void onError(Throwable error) {
Log.i("MyError",error.getMessage());
System.out.println(error.getMessage());
error.printStackTrace();
}
});
}
@Override
public void updateMovie(Movie movie) {
mMovieService.updateMovie(movie)
.subscribeOn(Schedulers.io())
.flatMap(new SingleResponseFlatMap<>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Movie>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Movie movie) {
System.out.println("Обновление прошло успешно!");
}
@Override
public void onError(Throwable error) {
Log.i("MyError",error.getMessage());
System.out.println(error.getMessage());
error.printStackTrace();
}
});
}
@Override
public void createMovie(Movie movie) {
mMovieService.createMovie(movie)
.subscribeOn(Schedulers.io())
.flatMap(new SingleResponseFlatMap<>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Movie>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Movie movie) {
System.out.println("Создание прошло успешно!");
}
@Override
public void onError(Throwable error) {
Log.i("MyError",error.getMessage());
System.out.println(error.getMessage());
error.printStackTrace();
}
});
}
@Override
public void deleteMovie(Integer id) {
mMovieService.deleteMovie(id)
.subscribeOn(Schedulers.io())
.flatMap(new SingleResponseFlatMap<>())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Boolean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Boolean aBoolean) {
System.out.println("Создание прошло успешно!");
}
@Override
public void onError(Throwable error) {
Log.i("MyError",error.getMessage());
System.out.println(error.getMessage());
error.printStackTrace();
}
});
}
}
| f0207aa6d78f3a0a53f19d49a64e46d2887ddf50 | [
"Java"
] | 7 | Java | Ivan1998popov/WS_Home_work6 | 23f90f4367362d460170e41527a0c9bd44cb4e82 | 2f3c318cde6986170288f160a91bc205abc71c33 |
refs/heads/main | <repo_name>RaphaelBhnk/Projet-Theorie-des-graphes<file_sep>/code/Sommet.cpp
#include <iostream>
#include <queue>
#include <stack>
#include<unordered_map>
#include<unordered_set>
#include "sommet.h"
/** \brief :constructeur de la classe sommet
* \param int identifiant
* \param double la position x
* \param double la position y
* \return
*
*/
Sommet::Sommet(int id,double x,double y):m_id{id},m_x{x},m_y{y}
{
}
/** \brief :affiche les infos des sommets du graphe
* \param
* \return
*
*/
void Sommet::afficherData() const{
std::cout<<" "<<m_id<<" : "<<"(x,y)=("<<m_x<<","<<m_y<<")"<<std::endl;
}
/** \brief :destructeur de la classe sommet
* \param
* \return
*
*/
Sommet::~Sommet()
{
//dtor
}
/** \brief :recuper la position x d'un sommet
* \param
* \return double m_x
*
*/
double Sommet::getx() const
{
return m_x;
}
/** \brief :recuper la position y d'un sommet
* \param
* \return double m_y
*
*/
double Sommet::gety() const
{
return m_y;
}
/** \brief :recuper l'etat d'un sommet(pour Dijkstra)
* \param
* \return bool m_etat
*
*/
void Sommet::setetat(bool etat)
{
m_etat=etat;
}
<file_sep>/code/Arete.cpp
#include "Arete.h"
/** \brief : Constructeur de la classe Arete
*
* \param int id
* \param int sommet initial
* \param int sommet final
* \return
*
*/
Arete::Arete(int id,int s1,int s2)
{
m_id=id;
m_s1=s1;
m_s2=s2;
m_ok=0;
}
/** \brief : récupere le nombre de pondération
*
* \param
* \return int m_pond.size()
*
*/
int Arete::getaillepond()
{
return m_pond.size();
}
/** \brief : recupere la ponderation
*
* \param int i
* \return float la ponderation i
*
*/
float Arete::getpond(int i)
{
return m_pond[i];
}
/** \brief : Afficher les infos des aretes de mon graphe
*
* \param
* \return
*
*/
void Arete::afficherArete() const{
std::cout<<" "<<m_id<<" : "<<"(s1,s2)=("<<m_s1<<","<<m_s2<<")";
std::cout<<"Ponderation :";
for(int i=0;i<m_pond.size();i++)
{
std::cout<<" "<<m_pond[i];
}
std::cout<<std::endl;
}
/** \brief :Destructeur de la classe Arete
*
* \param
* \return
*
*/
Arete::~Arete()
{
//dtor
}
/** \brief :modifier la valeur de la ponderation i
*
* \param float i
* \return
*
*/
void Arete::pushpond(float i)
{
m_pond.push_back(i);
}
/** \brief :recupere le sommet initial de l'arete
*
* \param
* \return int m_s1
*
*/
int Arete::gets1() const
{
return m_s1;
}
/** \brief :recupere le sommet final de l'arete
*
* \param
* \return int m_s2
*
*/
int Arete::gets2() const
{
return m_s2;
}
/** \brief :recupere le booleen pour savoir si l'arete doit être dessine(Kruskal)
*
* \param
* \return bool m_ok
*
*/
bool Arete::getok()
{
return m_ok;
}
/** \brief :modifier la valeur du booleen pour savoir si l'arete doit être dessine(Kruskal)
*
* \param bool a
* \return
*
*/
void Arete::setok(bool a)
{
m_ok=a;
}
<file_sep>/code/Sommet.h
#ifndef SOMMET_H
#define SOMMET_H
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
class Sommet
{
public:
///constructeur qui reçoit en params les données du sommet
Sommet(int,double,double);
void afficherData() const;
double getx() const;
double gety() const;
~Sommet();
void setetat(bool etat);
protected:
private:
/// Données spécifiques du sommet
int m_id; // Identifiant
double m_x, m_y; // Position
bool m_etat; // Etat du sommet (visité ou non)
};
#endif // SOMMET_H
<file_sep>/code/main.cpp
#include <iostream>
#include "graphe.h"
int main()
{
Svgfile svgout;
graphe g2("broadway.txt","broadway_weights_0.txt");
g2.afficher(svgout);
g2.bruteforce();
g2.kruskal(svgout);
g2.optimum1(svgout);
return 0;
}
<file_sep>/code/Graphe.cpp
#include <fstream>
#include <iostream>
#include <algorithm>
#include "graphe.h"
#include "list"
#include "sommet.h"
#include <bitset>
#include "math.h"
/** \brief :constructeur de la classe graphe qui recupere les données des deux fichiers textes pour ensuite les stocker dans
* un tableau d'aretes et un tableau de sommets
* \param std::string nomFichier
* \param std::string Fichier2
* \return
*
*/
graphe::graphe(std::string nomFichier, std::string Fichier2)
{
std::ifstream ifs{nomFichier};
if (!ifs)
throw std::runtime_error( "Impossible d'ouvrir en lecture " + nomFichier );
int ordre;
ifs >> ordre;
if ( ifs.fail() )
throw std::runtime_error("Probleme lecture ordre du graphe");
int id,id2;
double x,y;
//lecture des sommets
for (int i=0; i<ordre; ++i)
{
ifs>>id;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données sommet");
ifs>>x;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données sommet");
ifs>>y;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données sommet");
m_sommets.push_back(new Sommet(id,x,y));
}
std::ifstream ifs2{Fichier2};
if (!ifs2)
throw std::runtime_error( "Impossible d'ouvrir en lecture " + Fichier2 );
int taille, taille2;
ifs >> taille;
if ( ifs.fail() )
throw std::runtime_error("Probleme lecture taille du graphe");
ifs2 >> taille2;
if(ifs2.fail())
throw std::runtime_error("Probleme lecture données arete");
if(taille != taille2)
throw std::runtime_error("Les fichiers ne correspondeng pas");
int p;
ifs2>>p;
if(ifs2.fail())
throw std::runtime_error("Probleme lecture données arete");
int s1,s2;
std::vector<float> pond;
for(int i=0; i<p; i++)
{
pond.push_back(0);
}
//lecture des aretes
for (int i=0; i<taille; ++i)
{
//lecture des ids des deux extrémités
ifs>>id;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données arete");
ifs>>s1;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données arete");
ifs>>s2;
if(ifs.fail())
throw std::runtime_error("Probleme lecture données arete");
ifs2>>id2;
if(ifs2.fail())
throw std::runtime_error("Probleme lecture données arete");
for(int i=0; i<p; i++)
{
ifs2>>pond[i];
if(ifs2.fail())
throw std::runtime_error("Probleme lecture données arete");
}
m_tabarete.push_back(new Arete(id,s1,s2));
for(int i=0; i<p; i++)
{
m_tabarete[id]->pushpond(pond[i]);
}
}
}
/** \brief : Affiche: -les sommets et aretes du graphes avec les pondérations
* -le repere pour Pareto
* \param Svgfile &svgout
* \return
*
*/
void graphe::afficher(Svgfile &svgout)
{
m_ymax=0.0;
double ymin;
int cpt=0;
int cpt2=0;
std::cout<<"graphe : "<<std::endl;
std::cout<<"ordre : "<<m_sommets.size()<<std::endl;
for(unsigned int i=0; i<m_sommets.size(); i++)
{
std::cout<<"Sommet :";
m_sommets[i] -> afficherData();
std::cout<<std::endl;
}
std::cout<<"Taille : "<<m_tabarete.size()<<std::endl;
for (unsigned int i=0; i<m_tabarete.size(); ++i)
{
std::cout<<"Arete :";
m_tabarete[i]->afficherArete();
std::cout<<std::endl;
}
for (int i=0; i<m_tabarete.size(); ++i)
{
svgout.addLine(m_sommets[m_tabarete[i]->gets1()]->getx(),m_sommets[m_tabarete[i]->gets1()]->gety(),m_sommets[m_tabarete[i]->gets2()]->getx(),m_sommets[m_tabarete[i]->gets2()]->gety(),2,"black");
svgout.addText3((m_sommets[m_tabarete[i]->gets1()]->getx()+m_sommets[m_tabarete[i]->gets2()]->getx())/2,((m_sommets[m_tabarete[i]->gets1()]->gety()+m_sommets[m_tabarete[i]->gets2()]->gety())/2)-5,i,"red");
}
for(int i=0; i<m_sommets.size(); i++)
{
svgout.addDisk(m_sommets[i]->getx(),m_sommets[i]->gety(),10,"white");
svgout.addCircle(m_sommets[i]->getx(),m_sommets[i]->gety(),10,2,"black");
if(i>9)
{
svgout.addText3(m_sommets[i]->getx()-8,m_sommets[i]->gety()+5,i,"blue");
}
else
svgout.addText3(m_sommets[i]->getx()-3,m_sommets[i]->gety()+5,i,"blue");
}
for(int i=0;i<m_sommets.size();i++)
{
if(m_sommets[i]->getx()>m_xmax)
{
m_xmax=m_sommets[i]->getx();
}
}
ymin=m_sommets[0]->gety();
for(int i=1;i<m_sommets.size();i++)
{
if(m_sommets[i]->gety()<ymin)
{
ymin=m_sommets[i]->gety();
}
}
for(int i=1;i<m_sommets.size();i++)
{
if(m_sommets[i]->gety()>m_ymax)
{
m_ymax=m_sommets[i]->gety();
}
}
for (int i=0; i<m_tabarete.size(); ++i)
{
cpt2=0;
svgout.addText(m_xmax+100,ymin+cpt*30,"Arete:","black");
svgout.addText3(m_xmax+150,ymin+cpt*30,i,"black");
svgout.addText(m_xmax+200,ymin+cpt*30,"ponderation:","black");
for(int j=0;j<m_tabarete[0]->getaillepond();j++)
{
svgout.addText4(m_xmax+300+100*cpt2,ymin+cpt*30,m_tabarete[i]->getpond(j),"black");
cpt2++;
}
cpt++;
}
m_xmax=m_xmax+800;
svgout.addLine(m_xmax,100,m_xmax,800,2,"black");
svgout.addLine(m_xmax,100,m_xmax-10,100+15,2,"black");
svgout.addLine(m_xmax,100,m_xmax+10,100+15,2,"black");
svgout.addLine(m_xmax,800,m_xmax+700,800,2,"black");
svgout.addLine(m_xmax+700,800,m_xmax+700-15,800-10,2,"black");
svgout.addLine(m_xmax+700,800,m_xmax+700-15,800+10,2,"black");
svgout.addText(m_xmax+20,100,"cout 2","black");
svgout.addText(m_xmax+700,830,"cout 1","black");
}
/*void graphe::pareto()
{
std::bitset<1000> cas;
std::vector<std::bitset<1000>> cas_admissible;
std::vector<std::bitset<1000>> sol;
std::vector<std::string>liste_sommet;
liste_sommet.push_back("0");
bool ajout1=true; /// Verification pour ajout du sommet de depart
bool ajout2=true; /// Verification pour ajout du sommet d'arrivée
for( int i=0; i<pow(2,m_tabarete.size()); ++i) /// Filtrage cycle
{
cas=i;
if(cas.count()==m_sommets.size()-1)
{
//std::cout<<cas<<std::endl;
cas_admissible.push_back(cas);
}
}
for(std::size_t i=0; i<cas_admissible.size(); ++i) /// Filtrage connexité
{
for(std::size_t j=0; j<m_tabarete.size(); ++j)
{
if(cas_admissible[i][j]==true)
{
for(std::size_t k=0; k<liste_sommet.size(); ++k)
{
if(m_tabarete[j]->gets1()==liste_sommet[k]){ajout1=false;} /// Si sommet de depart deja contenu dans le vecteur
if(m_tabarete[j]->gets2()==liste_sommet[k]){ajout2=false;} /// Si sommet d'arrivée deja contenur dans le vecteur
}
if(ajout1==true)
{
liste_sommet.push_back(m_tabarete[j]->gets1());
std::cout<<cas_admissible[i]<<std::endl;
}
if(ajout2==true)
{
liste_sommet.push_back(m_tabarete[j]->gets2());
std::cout<<cas_admissible[i]<<std::endl;
}
}
}
if(liste_sommet.size()-1==m_sommets.size())
{
std::cout<<cas_admissible[i]<<std::endl;
sol.push_back(cas_admissible[i]);
}
}
}
*/
/** \brief : Filtre tous les chemins connexes et sans cycle et stocke tous ces chemins dans un vector<vector<bool>>
*
* \param
* \return
*
*/
void graphe::bruteforce()
{
// std::vector<std::vector<int>> cas;
std::vector<std::vector<int>> cas2;
// std::vector<std::vector<int>> casfinal;
/* for(int i=0; i<k3; i++)
{
std::vector<int> kk(k2,1);
for(int j=0; j<i; j++)
kk[j] = 0;
do
{
cas.push_back(kk);
g3++;
}
while(std::next_permutation(kk.begin(),kk.end()));
}
for(int i=0; i<k3; i++) //FILTRE CYCLES
{
p=0;
for(int j=0; j<k2; j++)
{
if(cas[i][j]==1)
{
p++;
}
}
if(p==k-1)
{
cas2.push_back(cas[i]);
g1++;
}
}*/
// int n = m_sommets.size();
//int o = m_sommets.size()-1;
std::vector<bool> cas(m_tabarete.size(),true);
std::vector<std::vector<bool>> casfin;
// std::vector<std::vector<bool>> casfinal;
for(int j=0; j<m_tabarete.size()-(m_sommets.size()-1);j++)
{
cas[j] = false;
}
do{
casfin.push_back(cas);
}while(std::next_permutation(cas.begin(),cas.end()));
/*
for(int i=0;i<casfin.size();i++)
{
for(int j=0;j<m_sommets.size()-1;j++)
std::cout<<casfin[i][j];
}
*/
//filtre conexite
/* for(unsigned int i=0; i<casfin.size(); i++)
{
p=0;
for(int t=0; t<m_tabarete.size(); t++)
{
tab[t]=t;
}
for(int j=0; j<m_tabarete.size(); j++)
{
if(casfin[i][j]==1)
{
for(int z=0; z<m_tabarete.size(); z++)
{
if(m_tabarete[j]->gets1()==z)
{
tab[z]=-1;
}
if(m_tabarete[j]->gets2()==z)
{
tab[z]=-1;
}
}
}
}
for(int z=0; z<m_tabarete.size(); z++)
{
if(tab[z]==-1)
{
p++;
}
}
if(p==m_sommets.size())
{
casfinal.push_back(casfin[i]);
g++;
}
}
// std::cout<<m_casfinal.size();
*/
//dernier filtre
std::vector<int> tabconnex(m_sommets.size(),0);
int cpt,premier;
for(int i=0;i<casfin.size();i++)
{
for(unsigned int y=0;y<tabconnex.size();y++)
{
tabconnex[y]=y;
}
cpt=0;
for(int j=0;j<m_tabarete.size();j++)
{
if(casfin[i][j]==true)
{
premier=tabconnex[m_tabarete[j]->gets1()];
tabconnex[m_tabarete[j]->gets1()]=tabconnex[m_tabarete[j]->gets2()];
for(int d=0;d<tabconnex.size();d++)
{
if(tabconnex[d]==premier)
{
tabconnex[d]=tabconnex[m_tabarete[j]->gets2()];
}
}
}
}
for(int q=0;q<tabconnex.size()-1;q++)
{
if(tabconnex[q]==tabconnex[q+1])
{
cpt++;
}
}
if(cpt==tabconnex.size()-1)
{
m_casfinal.push_back(casfin[i]);
}
}
std::cout<<"Il y a: ";
std::cout<<m_casfinal.size();
std::cout<<" solutions";
std::vector<float>pond_arete;
std::vector<std::vector<float>>ponde_toutes_les_aretes;
std::vector<float>poid_t;
int taille=m_tabarete[0]->getaillepond();
for(int z=0;z<taille;z++)
{
poid_t.push_back(0.0);
}
for(int i=0;i<m_casfinal.size();i++)
{
for(int j=0;j<m_tabarete.size();j++)
{
if(m_casfinal[i][j]==true)
{
for(int k=0;k<taille;k++)
{
pond_arete.push_back(m_tabarete[j]->getpond(k));
}
ponde_toutes_les_aretes.push_back(pond_arete);
pond_arete.clear();
}
}
for(int r=0;r<taille;r++)
{
for(int a=0;a<ponde_toutes_les_aretes.size();a++)
{
poid_t[r]=poid_t[r]+ponde_toutes_les_aretes[a][r];
}
}
m_poids.push_back(poid_t);
for(int z=0;z<taille;z++)
{
// std::cout<<poid_t[z];
poid_t[z]=0.0;
}
//std::cout<<std::endl;
}
for(int q=m_poids.size()-1;q>-1;q--)
{
for(int s=0;s<taille;s++)
{
if(q>0)
{m_poids[q][s]=m_poids[q][s]-m_poids[q-1][s];
}
}
}
}
/*
void graphe::optimum()
{
std::vector<float>pond_arete;
std::vector<std::vector<float>>ponde_toutes_les_aretes;
std::vector<float>poid_t;
std::vector<std::vector<float>>m_poids;
for(int i=0; i<m_tabarete[0]->getaillepond(); ++i)
{
poid_t.push_back(0.0);
}
for(unsigned int z=0; z<m_casfinal.size(); z++)
{
for(unsigned int v=0; v<m_tabarete.size(); v++)
{
if(m_casfinal[z][v]==1)
{
for(int i=0; i<m_tabarete[v]->getaillepond(); ++i)
{
pond_arete.push_back(m_tabarete[v]->getpond(i));
}
ponde_toutes_les_aretes.push_back(pond_arete);
pond_arete.clear();
}
for(int i=0; i<m_tabarete[v]->getaillepond(); ++i)
{
poid_t[i]+=ponde_toutes_les_aretes[v][i];
}
m_poids.push_back(poid_t);
for(int i=0; i<m_tabarete[v]->getaillepond(); ++i)
{
poid_t[i]=0;
}
}
}
for(int i=0;i<m_poids.size();i++)
{
for(int j=0;j<m_tabarete[0]->getaillepond();j++)
{
std::cout<<m_poids[i][j];
}
std::cout<<std::endl;
}
}
*/
/** \brief : Faire l'optimum de Pareto et le dessiner dans le repère. Appliquer un coef pour pas avoir des points en dehors du repère.
*
* \param Svgfile &svgout
* \return
*
*/
void graphe::optimum1(Svgfile &svgout)
{
std::vector<float>pond_arete;
std::vector<std::vector<float>>ponde_toutes_les_aretes;
std::vector<float>poid_t;
int taille=m_tabarete[0]->getaillepond();
double m_xmax=0.0;// pour bien placer le repere dans le svg
float cout1max=0.0;//
float cout2max=0.0;
int indice;
float minimum;
// std::cout<<"Poids 1:"<<m_poids[q][0]<<" poids2:"<<m_poids[q][1];
// std::cout<<std::endl;
for(int i=0;i<m_sommets.size();i++)
{
if(m_sommets[i]->getx()>m_xmax)
{
m_xmax=m_sommets[i]->getx();
}
}
m_xmax=m_xmax+800;
for(int q=0;q<m_poids.size();q++)
{
for(int s=0;s<taille;s++)
{
if(s==0)
{
if(cout1max<m_poids[q][s])
{
cout1max=m_poids[q][s];
}
}
if(s==1)
{
if(cout2max<m_poids[q][s])
{
cout2max=m_poids[q][s];
}
}
}
}
cout1max=cout1max/600;
cout2max=cout2max/600;
for(int q=0;q<m_poids.size();q++)
{
for(int s=0;s<taille;s++)
{
if(s==0)
{
m_poids[q][s]=m_poids[q][s]/cout1max;
}
else
{
m_poids[q][s]=m_poids[q][s]/cout2max;
}
}
//if(q!=m_poids.size()-1)
// {
// if((m_poids[q][0]==m_poids[q+1][0])&&(m_poids[q][1]==m_poids[q+1][1]))
//{
//svgout.addDisk(m_poids[q][0]+m_xmax,800-m_poids[q][1],100,"green");
// }
// else{svgout.addDisk(m_poids[q][0]+m_xmax,800-m_poids[q][1],4,"green");}
//}
//else{svgout.addDisk(m_poids[q][0]+m_xmax,800-m_poids[q][1],4,"green");}
svgout.addDisk(m_poids[q][0]+m_xmax,800-m_poids[q][1],5,"green");
}
minimum=m_poids[0][0];
for(int q=0;q<m_poids.size();q++)
{
if(minimum>m_poids[q][1])
{
minimum=m_poids[q][1];
indice=q;
}
if(minimum==m_poids[q][1])
{
if(m_poids[q][0]<m_poids[indice][0])
{
indice=q;
}
}
}
svgout.addDisk(m_poids[indice][0]+m_xmax,800-m_poids[indice][1],5,"red");
float i1,i2,i4,i5;
i4=m_poids[indice][0];
i5=m_poids[indice][1];
//trier selon le cout 2 puis par cout 1 pour trouver l'optimum
for(int q=0;q<m_poids.size()-1;q++)
{
for(int q=0;q<m_poids.size()-1;q++)
{
if(m_poids[q][1]>m_poids[q+1][1])
{
for(int s=0;s<taille;s++)
{
minimum=m_poids[q][s];
m_poids[q][s]=m_poids[q+1][s];
m_poids[q+1][s]=minimum;
}
}
}
}
for(int q=0;q<m_poids.size()-1;q++)
{
for(int q=0;q<m_poids.size()-1;q++)
{
if(m_poids[q][1]==m_poids[q+1][1])
{
if(m_poids[q][0]>m_poids[q+1][0])
for(int s=0;s<taille;s++)
{
minimum=m_poids[q][s];
m_poids[q][s]=m_poids[q+1][s];
m_poids[q+1][s]=minimum;
}
}
}
}
i1=m_poids[0][1];
i2=m_poids[0][0];
for(int q=0;q<m_poids.size()-1;q++)
{
if(m_poids[q][1]!=m_poids[q+1][1])
{
i1=m_poids[q+1][1];
if(i2>m_poids[q+1][0])
{
i2=m_poids[q+1][0];
svgout.addDisk(i2+m_xmax,800-i1,5,"red");
svgout.addLine(i2+m_xmax,800-i1,i4+m_xmax,800-i5,2,"red");
i4=m_poids[q+1][0];
i5=m_poids[q+1][1];
}
}
}
}
/** \brief : Destructeur de la classe graphe
*
* \param Svgfile &svgout
* \return
*
*/
graphe::~graphe()
{
//dtor
}
/** \brief : Afficher les graphes de Kruskal en fonction des pondérations
*
* \param Svgfile &svgout
* \return
*
*/
void graphe::kruskal(Svgfile &svgout)
{
std::vector<std::vector<int>> cas2;
std::vector<bool> cas(m_tabarete.size(),true);
std::vector<std::vector<bool>> casfin;
for(int j=0; j<m_tabarete.size()-m_sommets.size()-1;j++)
{
cas[j] = false;
}
do{
casfin.push_back(cas);
}while(std::next_permutation(cas.begin(),cas.end()));
//dernier filtrestd::cout
std::vector<int> tabconnex(m_sommets.size(),0);
int cpt,premier;
float compteur=0.0;
float compteur2=0.0;
for(int i=0;i<casfin.size();i++)
{
for(unsigned int y=0;y<tabconnex.size();y++)
{
tabconnex[y]=y;
}
cpt=0;
for(int j=0;j<m_tabarete.size();j++)
{
if(casfin[i][j]==true)
{
premier=tabconnex[m_tabarete[j]->gets1()];
tabconnex[m_tabarete[j]->gets1()]=tabconnex[m_tabarete[j]->gets2()];
for(int d=0;d<tabconnex.size();d++)
{
if(tabconnex[d]==premier)
{
tabconnex[d]=tabconnex[m_tabarete[j]->gets2()];
}
}
}
}
for(int q=0;q<tabconnex.size()-1;q++)
{
if(tabconnex[q]==tabconnex[q+1])
{
cpt++;
}
}
if(cpt==tabconnex.size()-1)
{
m_casfinal.push_back(casfin[i]);
}
}
int indice;
bool a=1;
float minimum;
minimum=m_poids[0][0];
//Kruskal pour cout 2
for(int i=0;i<m_tabarete.size();i++)
{
m_tabarete[i]->setok(0);
}
//Kruskal pour cout 1
for(int q=0;q<m_poids.size();q++)
{
if(minimum>m_poids[q][1])
{
minimum=m_poids[q][1];
indice=q;
}
if(minimum==m_poids[q][1])
{
if(m_poids[q][0]<m_poids[indice][0])
{
indice=q;
}
}
}
for(int i=0;i<m_tabarete.size();i++)
{
if(m_casfinal[indice][i]==1)
{
m_tabarete[i]->setok(a);
}
}
for(int i=0;i<m_tabarete.size();i++)
{
if(m_tabarete[i]->getok()==1)
{
svgout.addLine(m_sommets[m_tabarete[i]->gets1()]->getx(),m_sommets[m_tabarete[i]->gets1()]->gety()+2*m_ymax+200,m_sommets[m_tabarete[i]->gets2()]->getx(),m_sommets[m_tabarete[i]->gets2()]->gety()+2*m_ymax+200,2,"red");
compteur=m_poids[indice][1];
compteur2=m_poids[indice][0];
}
}
for(int i=0; i<m_sommets.size(); i++)
{
svgout.addDisk(m_sommets[i]->getx(),m_sommets[i]->gety()+2*m_ymax+200,10,"white");
svgout.addCircle(m_sommets[i]->getx(),m_sommets[i]->gety()+2*m_ymax+200,10,2,"black");
svgout.addText3(m_sommets[i]->getx()-3,m_sommets[i]->gety()+5+2*m_ymax+200,i,"blue");
}
svgout.addText4(m_xmax+300-800,2*m_ymax+400,compteur,"blue");
svgout.addText4(m_xmax+250-800,2*m_ymax+400,compteur2,"blue");
svgout.addText(m_xmax+100-800,2*m_ymax+400,"PONDERATION:","blue");
for(int i=0;i<m_tabarete.size();i++)
{
m_tabarete[i]->setok(0);
}
//Kruskal pour cout 1
minimum=m_poids[0][0];
for(int q=0;q<m_poids.size();q++)
{
if(minimum>m_poids[q][0])
{
minimum=m_poids[q][0];
indice=q;
}
if(minimum==m_poids[q][0])
{
if(m_poids[q][1]<m_poids[indice][1])
{
indice=q;
}
}
}
for(int i=0;i<m_tabarete.size();i++)
{
if(m_casfinal[indice][i]==1)
{
m_tabarete[i]->setok(a);
}
}
for(int i=0;i<m_tabarete.size();i++)
{
if(m_tabarete[i]->getok()==1)
{
svgout.addLine(m_sommets[m_tabarete[i]->gets1()]->getx(),m_sommets[m_tabarete[i]->gets1()]->gety()+m_ymax+200,m_sommets[m_tabarete[i]->gets2()]->getx(),m_sommets[m_tabarete[i]->gets2()]->gety()+m_ymax+200,2,"red");
compteur=m_poids[indice][1];
compteur2=m_poids[indice][0];
}
}
for(int i=0; i<m_sommets.size(); i++)
{
svgout.addDisk(m_sommets[i]->getx(),m_sommets[i]->gety()+m_ymax+200,10,"white");
svgout.addCircle(m_sommets[i]->getx(),m_sommets[i]->gety()+m_ymax+200,10,2,"black");
svgout.addText3(m_sommets[i]->getx()-3,m_sommets[i]->gety()+5+m_ymax+200,i,"blue");
}
svgout.addText(100,m_ymax+200,"KRUSKAL","blue");
svgout.addText4(m_xmax+300-800,m_ymax+400,compteur,"blue");
svgout.addText4(m_xmax+250-800,m_ymax+400,compteur2,"blue");
svgout.addText(m_xmax+100-800,m_ymax+400,"PONDERATION:","blue");
}
void graphe::dijkstra()
{
//int sommet;
//std::cout<<"veuillez saisir un sommet:";
//std::cin>>sommet;
//faire un tableau de N*N avec N l'ordre du graphe
// int etapes=m_sommet.size();
// tab
// for(int=0;i<=etapes;i++)
/*Pour chaque sommet en partant du sommet de depart
faire une liste des arettes
pour chaque arettes
ajouter le poids de l'arette à la distance deja parcouru
noter le sommet précédent
interdire le sommet le sommet visité
recherche du chemin minimal dans les colonnes non interdites
recopier ce chemin dans la colonne de l'etape suivante
*/
//m_sommets.find(sommet)->setetat(true);
}
<file_sep>/code/Graphe.h
#ifndef GRAPHE_H
#define GRAPHE_H
#include <string>
#include <unordered_map>
#include "sommet.h"
#include "Arete.h"
#include "Svgfile.h"
class graphe
{
public:
///constructeur qui charge le graphe en mémoire
//format du fichier ordre/liste des sommets/taille/liste des arêtes
graphe(std::string, std::string);
~graphe();
void afficher(Svgfile &svgout) ;
void bruteforce();
void optimum1(Svgfile &svgout);
void kruskal(Svgfile &svgout);
void dijkstra();
protected:
private:
/// Le réseau est constitué d'une collection de sommets
std::vector<Sommet*>m_sommets;
std::vector<Arete*>m_tabarete;
std::vector<std::vector<bool>> m_casfinal;
std::vector<std::vector<float>> m_poids;
double m_ymax,m_xmax;
};
#endif // GRAPHE_H
<file_sep>/code/Arete.h
#ifndef ARETE_H
#define ARETE_H
#include <string>
#include <vector>
#include <iostream>
class Arete
{
public:
Arete(int,int,int);
void afficherArete()const;
~Arete();
int gets1() const;
int gets2() const;
void pushpond(float);
float getpond(int i);
int getaillepond();
bool getok();
void setok(bool);
protected:
private:
int m_id;
int m_s1;
int m_s2;
std::vector<float> m_pond;
bool m_ok;
};
#endif // ARETE_H
<file_sep>/README.md
# Projet-Theorie-des-graphes
Dessiner un graphe à partir de plusieurs sommets et arêtes:

Implémenter l'algorithme de Kruskal pour chaque pondération:

Réaliser un optimum de Pareto:

| 145ef494aaafca83954ce6d4d540f42d3cb10c00 | [
"Markdown",
"C++"
] | 8 | C++ | RaphaelBhnk/Projet-Theorie-des-graphes | 8c65e51988402a3a2184df3b66e8ce0dec2df840 | 9ca3551b36830af2f71f59c238c568bc42545f4d |
refs/heads/master | <repo_name>Ghernandez1991/SURFS-UP--SQL-Alchemy-<file_sep>/app.py
from flask import Flask, jsonify
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, desc
from sqlalchemy.sql import label
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# We can view all of the classes that automap found
Base.classes.keys()
# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station
# Create our session (link) from Python to the DB
session = Session(engine)
#open homeworkutd.ipynb import dict_precip, stations, dict_temps
stations_data = ["USC00519281", "USC00519397", "USC00513117", "USC00519523", "USC00516128", "USC00514830", "USC00511918", "USC00517948", "USC00518838"]
# 2. Create an app, being sure to pass __name__
app = Flask(__name__)
# 3. Define what to do when a user hits the index route
@app.route("/")
def home():
return (
f"Server received request for 'Home' page..."
f"Welcome to the Weather Station API <br/>"
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/<start><br/>"
f"/api/v1.0/<start>/<end><br/>"
)
# 4. Define what to do when a user hits the /about route
@app.route("/api/v1.0/precipitation")
def precipitation():
print("Server received request for 'precipitation' page...")
# Perform a query to retrieve the data and precipitation scores
results = session.query(Measurement.date, Measurement.prcp).\
filter(Measurement.date > '2016-08-23').\
order_by(Measurement.date).all()
# Save the query results as a Pandas DataFrame and set the index to the date colum
dates = [result[0] for result in results]
precipitation = [result[1] for result in results]
# Create a zip object from two lists
dates_precip = zip(dates, precipitation)
# Create a dictionary from zip object
dict_precip = dict(dates_precip)
dict_precip1 = dict_precip
return jsonify(dict_precip1)
@app.route("/api/v1.0/stations")
def stations():
print("Server received request for 'stations' page...")
stations1 = stations_data
return jsonify(stations1)
@app.route("/api/v1.0/tobs")
def tobs():
print("Server received request for 'tobs' page...")
date_temps = session.query(Measurement.date, Measurement.tobs).\
filter(Measurement.date > '2016-08-23').\
order_by(Measurement.date).all()
#date_temps
dates_1 = [date_temp[0] for date_temp in date_temps]
temps_1= [date_temp[1] for date_temp in date_temps]
#temps_1
date_temps2 = zip(dates_1, temps_1)
# Create a dictionary from zip object
dict_temps = dict(date_temps2)
dict_temps1 = dict_temps
return jsonify(dict_temps1)
@app.route("/api/v1.0/<start>")
def start():
print("Server received request for 'start' page...")
return "Welcome to my start page!"
@app.route("/api/v1.0/<start>/<end>")
def end():
print("Server received request for 'end' page...")
return "Welcome to my end page!"
if __name__ == "__main__":
app.run(debug=True)
| b781a75e772c6d33a3fca70f05adea0c5969a553 | [
"Python"
] | 1 | Python | Ghernandez1991/SURFS-UP--SQL-Alchemy- | db59e1aadf513fb167b83c3ff5846348e18cf1e5 | 9e38164d369ee2cccec64765718ef7f2018af036 |
refs/heads/main | <file_sep>restfull_api_for_books source code
=============================
## General info
This project is web accessible api built in django and django rest framework
<file_sep>from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import BookSerializer
from .models import Book
# Getting all books
@api_view(['GET'])
def books(request):
tasks = Book.objects.all().order_by('-id')
serializer = BookSerializer(tasks, many=True)
return Response(serializer.data)
# Getting one book
@api_view(['GET'])
def book_detail(request, pk):
tasks = Book.objects.get(id=pk)
serializer = BookSerializer(tasks, many=False)
return Response(serializer.data)
# Adding new book
@api_view(['POST'])
def create_book(request):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
# Updating existing book
@api_view(['POST'])
def update_book(request, pk):
task = Book.objects.get(id=pk)
serializer = BookSerializer(instance=task, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
# Deleting a book
@api_view(['DELETE'])
def delete_book(request, pk):
task = Book.objects.get(id=pk)
task.delete()
return Response('Item succsesfully delete!')
<file_sep>from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
authors = models.CharField(max_length=200)
publisher = models.CharField(max_length=200)
publication_date = models.DateField()
<file_sep>from django.apps import AppConfig
class BooksStoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'books_store'
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('books/', views.books, name="task-list"),
path('book-detail/<str:pk>/', views.book_detail, name="book-detail"),
path('create-book/', views.create_book, name="create-book"),
path('update-book/<str:pk>/', views.update_book, name="update-book"),
path('delete-book/<str:pk>/', views.delete_book, name="delete-book"),
]
| f8775c0a9939c09bba0597743d76955feff46c3d | [
"Markdown",
"Python"
] | 5 | Markdown | ZukhriddinMirzajanov/restfull_api_for_books | 0e80aafc0983989493d2a23ca9d9e5631806dc13 | a256f150349ac0124e4fd13b649aa2cc5c2d608d |
refs/heads/master | <repo_name>zachattack77/pets2<file_sep>/tmp/1bit9ydgc55de.3bejrbxme10ks.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New-Pet</title>
</head>
<body>
<h1>Order a Pet</h1>
<form action="" method="post">
<label class="col-sm-1 control-label"
>Pet Name</label>
<div class="col-sm-3">
<?php if (isset($invalidName)): ?>
<p>Please enter a valid name</p>
<?php endif; ?>
<input type="text" name="pet-name" <?php if (isset($name)): ?> value="<?= ($name) ?>"<?php endif; ?>>
</div>
<label class="col-sm-1 control-label"
for="pet-color">Pet Color</label>
<div class="col-sm-3">
<?php if (isset($invalidColor)): ?>
<p>Please enter a valid color</p>
<?php endif; ?>
<select class="form-control" name="pet-color" id="pet-color">
<option>-----Select-----</option>
<?php foreach (($colors?:[]) as $colorOption): ?>
<option <?php if ($colorOption == $color): ?>selected<?php endif; ?> value="<?= ($colorOption) ?>" > <?= ($colorOption) ?></option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-1 control-label">Pet Type</label>
<div class="col-sm-3">
<?php if (isset($invalidType)): ?>
<p>Please enter a valid Type</p>
<?php endif; ?>
<input type="text" name="pet-type" <?php if (isset($type)): ?>value="<?= ($type) ?>"<?php endif; ?>>
</div>
<button type="submit" name="submit">Submit</button>
</form>
<?php if ($success): ?>
<h2>Thank you for your order of a <?= ($type) ?> !</h2>
<?php endif; ?>
</body>
</html><file_sep>/tmp/1bit9ydgc55de.1rf2bp8unhuoj.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Results</title>
</head>
<body>
<h1>Thank you for ordering a <?= ($color) ?> <?= ($animal) ?>!</h1>
</body>
</html> | 4ee1d68e4bedd6ea7c089039af3dcc6e0381f156 | [
"PHP"
] | 2 | PHP | zachattack77/pets2 | d372e22cda797b8b972465b429ea59457bd68c91 | c9baf8f11e43dd611ca753b5bdd42c04457a58fa |
refs/heads/master | <file_sep>Visualizing Data with Leaflet
## Background

The USGS is responsible for providing scientific data about natural hazards, the health of our ecosystems and environment; and the impacts of climate and land-use change. Their scientists develop new methods and tools to supply timely, relevant, and useful information about the Earth and its processes.
This project uses Javascript and Leaflet to create visual maps of earthquake data collected from the USGS.

<file_sep>
url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson"
//function to create maps
function createMap(data, legend){
//create base tile layers
var satMap = L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", {
attribution: "Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>",
maxZoom: 8,
id: "mapbox.satellite",
accessToken: API_KEY});
var darkMap = L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", {
attribution: "Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>",
maxZoom: 18,
id: "mapbox.dark",
accessToken: API_KEY});
var lightMap = L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", {
attribution: "Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>",
maxZoom: 18,
id: "mapbox.light",
accessToken: API_KEY});
//store base tile layers in dict
var baseMaps = {
"Satellite":satMap,
"Light Map":lightMap,
"Dark Map":darkMap
};
map = L.map('map', {
center: [37.733795,-122.446747],
zoom: 8,
layers: [satMap, lightMap, darkMap]
});
//create lines for tectonic plates
d3.json("/static/data/PB2002_plates.json", function(response) {
var plateData = L.geoJSON(response, {
pointToLayer: function (feature, latlng) {
},
fill: false,
color: "orange",
weight: "2"
})
overlayMaps = {
"Earthquakes": data,
"Tectonic Plates": plateData
}
//add layers to control center
L.control.layers(baseMaps, overlayMaps).addTo(map);
})
legend.addTo(map);
};
//function for coloring circles by magnitude
function getColor(d) {
return d > 8 ? '#7f0000' :
d > 7 ? '#b30000' :
d > 6 ? '#d7301f' :
d > 5 ? '#ef6548' :
d > 4 ? '#fc8d59' :
d > 3 ? '#fdbb84' :
d > 2 ? '#fdd49e' :
d > 1 ? '#fee8c8' :
'#fff7ec';
}
//function to create earthquake markers
function earthQMarkers(response){
var eqLayer = L.geoJSON(response, {
pointToLayer: function (feature, latlng) {
//set marker options according to earthquake magnitude
var cMarker = L.circleMarker(latlng, geojsonMarkerOptions = {
radius: feature.properties.mag *5,
fillColor: getColor(feature.properties.mag),
color: feature.properties.mag,
weight: 1,
opacity: 1,
fillOpacity: 0.8,
riseOnHover: true
});
return cMarker;
},
onEachFeature: function(feature, layer){
var date = new Date(feature.properties.time);
layer.bindPopup(`Place & Mag.: ${feature.properties.title} <br> Date: ${date}`)
}
});
//set up map legend
var legend = L.control({ position: "bottomright" });
legend.onAdd = function() {
var div = L.DomUtil.create("div", "info legend");
// create legend html table
var legendInfo = "<h1>Color Legend</h1>" +
"<div class=\"labels\">" +
"<table>" + "<tr>" +
"<th>Magnitude</th><th>Color</th>" + "</tr>" +
"<tr><td> 1-2 </td><td style='background-color:#fee8c8'> </td></tr>" +
"<tr><td> 2-3 </td><td style='background-color:#fdd49e'> </td></tr>" +
"<tr><td> 3-4 </td><td style='background-color:#fdbb84'> </td></tr>" +
"<tr><td> 4-5 </td><td style='background-color:#fc8d59'> </td></tr>" +
"<tr><td> 5-6 </td><td style='background-color:#ef6548'> </td></tr>" +
"<tr><td> 6-7 </td><td style='background-color:#d7301f'> </td></tr>" +
"<tr><td> 7-8 </td><td style='background-color:#b30000'> </td></tr>" +
"<tr><td> > 8 </td><td style='background-color:#7f0000'> </td></tr></table>" +
"</div>";
div.innerHTML = legendInfo;
// div.innerHTML += "<ul>" + "Mag: 1-2 " + "<html color='#fee8c8'> dddd </text>" + "</ul>";
return div;
};
//send data to create maps function
createMap(eqLayer, legend);
};
//function to create tectonic plate line layer
// function plateLines(){
// return(d3.json("/static/data/PB2002_plates.json", function(response) {
// var plateData = L.geoJSON(response, {
// pointToLayer: function (feature, latlng) {
// var plate = L.marker(latlng, {
// color: 'red'
// })
// return plate;
// }
// })
// return plateData;
// }));
// };
d3.json(url, earthQMarkers); | 9e16969940f330fe64a297421deb9988c409948f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kcdevillier/Leaflet | d0e3ce0ef225f937e14d15a01b92cb733ca163e7 | 17baa193a743b3c5fac67b82c17147bc3b0dabbd |
refs/heads/master | <repo_name>jpatton638/webdevassignmentb<file_sep>/register.php
<!DOCTYPE html>
<?php
// Create connection to server
$servername = "localhost";
$username = "root";
$password = "<PASSWORD>";
$dbname = "chollerton_tearooms";
$conn = new mysqli($servername, $username, $password, $dbname);
?>
<?php
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// Code to populate table with entries from form, checking if required fields are empty.
$forename = $_POST["forename"];
$surname = $_POST["surname"];
$postalAddress = $_POST["postalAddress"];
$landLineTelNo = $_POST["landLineTelNo"];
$mobileTelNo = $_POST["mobileTelNo"];
$email = $_POST["email"];
$sendMethod = $_POST["sendMethod"];
$sql = "INSERT INTO CT_expressedInterest
(forename, surname, postalAddress, landLineTelNo, mobileTelNo,
email, sendMethod)
VALUES ('$forename', '$surname', '$postalAddress', '$landLineTelNo', '$mobileTelNo',
'$email', '$sendMethod')";
if ($conn->query($sql) === TRUE)
{
//readfile("register.php");
}
else
{
echo "Error creating entry: " . $conn->error;
}
$conn->close();
//}
//}
?>
<html>
<!--Head specifies the title of the webpage, holds the meta tag and links it to the relevant stylesheet-->
<head>
<title>Chollerton Tearooms</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="tea.css" />
</head>
<!--Body holds all of the content on the page-->
<body>
<!--Header of the page includes the logo-->
<header>
<img id="logo" src="logo.jpg" alt="Chollerton Tearooms Logo">
</header>
<!--Nav holds the links for the webpage-->
<nav>
<ul class="nav">
<li class="button"><a href="index.html">Home</a></li>
<li class="button"><a href="findoutmore.html">Find out more</a></li>
<li class="button"><a href="offer.html">Offer</a></li>
<li class="button"><a href="#">Credits</a></li>
<li class="button"><a href="#">Admin</a></li>
<li class="button"><a href="./wireframe.pdf">Wireframe</a></li>
</ul>
</nav>
<!--Main holds all of the main content of the page-->
<main>
<!--Article holds all of the different articles in one area within the Main-->
<article>
<!--Article-container holds the relevant text and images of each individual article-->
<section class="article-container">
<div id="article-text">
<h1>Thank You!</h1>
<div class="article-paragraph">
<p>Thank you for registering for our Newsletter!</p>
<p>You have supplied us with the following details:</p>
<table>
<tr>
<td>Forename</td>
<td><?php echo $_POST['forename'];?></td>
</tr>
<tr>
<td>Surname</td>
<td><?php echo $_POST['surname'];?></td>
</tr>
<tr>
<td>Postal Address</td>
<td><?php echo $_POST['postalAddress'];?></td>
</tr>
<tr>
<td>Landline Number</td>
<td><?php echo $_POST['landLineTelNo'];?></td>
</tr>
<tr>
<td>Mobile Number</td>
<td><?php echo $_POST['mobileTelNo'];?></td>
</tr>
<tr>
<td>Email Address</td>
<td><?php echo $_POST['email'];?></td>
</tr>
<tr>
<td>Send Method</td>
<td><?php echo $_POST['sendMethod'];?></td>
</tr>
</table>
</div>
</div>
<div class="image-container">
<img class="article-image" src="./coffee.jpg" alt="Creamy Cappuccino" />
</div>
</section>
</article>
</main>
<!--Clearflix -->
<div class="clearfix">
</div>
<!--Footer holds further information thee user may desire-->
<footer>
<!--Footer-section divides the text blocks into easily distinguishable sections-->
<div class="footer-section">
<p><NAME></p>
<p>27 Greedwood Lane</p>
<p>Chollerton</p>
<p>Hexham</p>
<p>NE46 1EA</p>
</div>
<div class="footer-section">
<p>@2015 <NAME></p>
<p>All rights reserved.</p>
<p>For more information, contact us at:</p>
<p><EMAIL></p>
<p>01916875394</p>
</div>
</footer>
</body>
</html>
<file_sep>/chollertontest.php
<!DOCTYPE html>
<!-- PHP may have to be inserted here -->
<html>
<!--Head specifies the title of the webpage, holds the meta tag and links it to the relevant stylesheet-->
<head>
<title>Chollerton Tearooms</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./tea.css" />
</head>
<!--Body holds all of the content on the page-->
<body>
<!--Header of the page includes the logo-->
<header>
<img id="logo" src="./logo.jpg" alt="Chollerton Tearooms Logo">
</header>
<!--Nav holds the links for the webpage-->
<nav>
<ul class="nav">
<li class="button"><a href="index.html">Home</a></li>
<li class="button"><a href="findoutmore.html">Find out more</a></li>
<li class="button"><a href="offer.html">Offer</a></li>
<li class="button"><a href="#">Credits</a></li>
<li class="button"><a href="#">Admin</a></li>
<li class="button"><a href="./wireframe.pdf">Wireframe</a></li>
</ul>
</nav>
<!--Main holds all of the main content of the page-->
<main>
<!--Article holds all of the different articles in one area within the Main-->
<article>
<!--Article-container holds the relevant text and images of each individual article-->
<section class="article-container">
<div id="article-text">
<h1>Find Out More</h1>
<div class="article-paragraph">
<p>Thank you for visiting our website!</p>
<p>At Chollerton Tearooms, we strive to bring you the very best experience.</p>
<p>In order to keep up to date with the latest news and offers about the tearoom and events in the local area, </p>
<p>If you would like to find out more about Chollerton Tearooms and the services we offer, make sure to sign up to our newsletter for monthly updates!</p>
</div>
</div>
<div class="image-container">
<img class="article-image" src="./coffee.jpg" alt="<NAME>" />
</div>
</section>
<!--Article-container holds the relevant text and images of each individual article-->
<section class="article-container">
<div id="article-text">
<h2>Get More Information</h2>
<div class="article-paragraph">
<form action="/var/www/html/test/register.php" method="post" id="infoForm">
<fieldset>
<legend>Please enter your information to sign up</legend>
<label for="forename">Forename <strong>*</strong></label>
<input type="text" name="forename" id="forename" accesskey="f"/>
<!--<span class="error">* <?php // echo $forenameErr;?></span>-->
<label for="surname">Surname <strong>*</strong></label>
<input type="text" name="surname" id="surname" accesskey="s"/>
<!--<span class="error">* <?php // echo $surnameErr;?></span>-->
<label for="postalAddress">Postal Address</label>
<input type="text" name="postalAddress" id="postalAddress" accesskey="p"/>
<label for="landLineTelNo">Landline Number</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" accesskey="l"/>
<label for="mobileTelNo">Mobile Number</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" accesskey="m"/>
<label for="email">Email Address</label>
<input type="text" name="email" id="email" accesskey="e"/>
<label for="sendMethod">How would you prefer to be contacted? <strong>*</strong></label>
<select name="sendMethod" id="sendMethod" accesskey="m">
<option value=""></option>
<option value="email">Email</option>
<option value="post">Post</option>
<option value="sms">SMS</option>
</select>
<!--<span class="error">* <?php // echo $sendMethodErr;?></span>-->
<label for="tsAndCs">I accept the Terms and Conditions <strong>*</strong></label>
<input type="checkbox" name="tsAndCs" value="yes" id="tsAndCs"/>
<div id="mustComplete" accesskey="t">
<p>All fields maked with "<strong>*</strong>" must be filled</p>
</div>
</fieldset>
<p><input type="submit" value="Sign Up" name="submit" accesskey="d"/></p>
</form>
<!-- PHP may have to be insterted here -->
</div>
</div>
<div class="image-container">
<img class="article-image" src="./teaoffer.jpg" alt="Chollerton Home Brew" />
</div>
</section>
</article>
</main>
<!--Clearflix -->
<div class="clearfix">
</div>
<!--Footer holds further information thee user may desire-->
<footer>
<!--Footer-section divides the text blocks into easily distinguishable sections-->
<div class="footer-section">
<p><NAME></p>
<p>27 Greedwood Lane</p>
<p>Chollerton</p>
<p>Hexham</p>
<p>NE46 1EA</p>
</div>
<div class="footer-section">
<p><strong>@2015 <NAME></strong></p>
<p>All rights reserved.</p>
<p>For more information, contact us at:</p>
<p><EMAIL></p>
<p>01916875394</p>
</div>
</footer>
</body>
</html><file_sep>/chollertonconformation.php
<html>
<!--Head specifies the title of the webpage, holds the meta tag and links it to the relevant stylesheet-->
<head>
<title>Chollerton Tearooms</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./tea.css" />
</head>
<!--Body holds all of the content on the page-->
<body>
<!--Header of the page includes the logo-->
<header>
<img id="logo" src="./logo.jpg" alt="Chollerton Tearooms Logo">
</header>
<!--Nav holds the links for the webpage-->
<nav>
<ul class="nav">
<li class="button"><a href="index.html">Home</a></li>
<li class="button"><a href="findoutmore.html">Find out more</a></li>
<li class="button"><a href="offer.html">Offer</a></li>
<li class="button"><a href="#">Credits</a></li>
<li class="button"><a href="#">Admin</a></li>
<li class="button"><a href="./wireframe.pdf">Wireframe</a></li>
</ul>
</nav>
<!--Main holds all of the main content of the page-->
<main>
<!--Article holds all of the different articles in one area within the Main-->
<article>
<!--Article-container holds the relevant text and images of each individual article-->
<section class="article-container">
<div id="article-text">
<h1>Find Out More</h1>
<div class="article-paragraph">
<p>Thank you for registering for our Newsletter!</p>
<p>You have supplied up with the following details:</p>
<table border="1">
<tr>
<td>Forename</td>
<td><?php echo $_POST['forename']?></td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</div>
</div>
<div class="image-container">
<img class="article-image" src="./coffee.jpg" alt="Creamy Cappuccino" />
</div>
</section>
</article>
</main>
<!--Clearflix -->
<div class="clearfix">
</div>
<!--Footer holds further information thee user may desire-->
<footer>
<!--Footer-section divides the text blocks into easily distinguishable sections-->
<div class="footer-section">
<p><NAME></p>
<p>27 Greedwood Lane</p>
<p>Chollerton</p>
<p>Hexham</p>
<p>NE46 1EA</p>
</div>
<div class="footer-section">
<p><strong>@2015 <NAME></strong></p>
<p>All rights reserved.</p>
<p>For more information, contact us at:</p>
<p><EMAIL></p>
<p>01916875394</p>
</div>
</footer>
</body>
</html> | f5ca8ed093edf31c50df5db75132bd1d0d95da4c | [
"PHP"
] | 3 | PHP | jpatton638/webdevassignmentb | a9754f075d2a2102240fa71c1e984891c133dfcf | c652751a6ca05be7e1072e5d90beb48042d60903 |
refs/heads/master | <repo_name>aur-archive/yaffs2utils<file_sep>/PKGBUILD
# Maintainer: <NAME> <nous at archlinux dot us>
# 29 May 2010
pkgname=yaffs2utils
pkgver=0.2.9
pkgrel=1
pkgdesc="A collection of utilities to make/extract a YAFFS2/YAFFS1 image for Linux. Currently includes mkyaffs2, unyaffs2 and unspare2."
arch=('i686' 'x86_64')
url=('http://code.google.com/p/yaffs2utils')
license=('GPL2')
depends=()
makedepends=('gcc')
options=('strip')
source=(http://yaffs2utils.googlecode.com/files/$pkgver.tar.gz)
md5sums=('eb00dce4357dae09c1cc0e16478095f2')
build() {
cd $srcdir/$pkgver
make
}
package() {
cd $srcdir/$pkgver
mkdir -p $pkgdir/usr/bin
install -m 0755 $srcdir/$pkgver/mkyaffs2 $pkgdir/usr/bin/
install -m 0755 $srcdir/$pkgver/unyaffs2 $pkgdir/usr/bin/
install -m 0755 $srcdir/$pkgver/unspare2 $pkgdir/usr/bin/
}
| 11dbf310c64a75ca4d18f819347372e42a79fe3d | [
"Shell"
] | 1 | Shell | aur-archive/yaffs2utils | 87dccc350cc6702f1320a464af7e5c5efce64d0b | 1d47f8469efed5f00ae96c7618a08b4e929aa9cd |
refs/heads/master | <repo_name>SangNong/arduino-test<file_sep>/arduino-test.ino
#include <Servo.h>
const int sampleWindow = 250;
unsigned int clap;
boolean isOff = true;
boolean readVolt = true;
int i=0;
Servo LightSwitch;
void setup() {
Serial.begin(9600);
LightSwitch.attach (5);
LightSwitch.write (10);
// put your setup code here, to run once:
}
void loop()
{
// put your main code here, to run repeatedly:
unsigned long start = millis();
unsigned int peakToPeak = 0;
unsigned int signalMax=0;
unsigned int signalMin=1024;
//collect data for 250 miliseconds
Serial.println ("loop");
while (millis() - start < sampleWindow)
{
clap = analogRead (1);
//Serial.println(claps;
if (clap < 1024) //this is the max of the 10-bit ADC so this loop will inlcude all readings
{
if (clap > signalMax)
{
signalMax = clap;
}
else if (clap < signalMin)
{
signalMin = clap;
}
}
}
peakToPeak = signalMax - signalMin;
double volts = (peakToPeak * 3.3) / 1024; //convert to volts
Serial.println(volts);
Serial.println(readVolt);
delay (200);
if (volts >= 1.5)
{
//turn on LED
//readVolt =false;
if (isOff){
Serial.println(i);
LightSwitch.write(10);
delay(50);
Serial.println("Lights On");
Serial.println(isOff);
isOff = false;
Serial.println(isOff);
}
else{
Serial.println(i);
LightSwitch.write(160);
delay(50);
Serial.println("Lights out");
isOff = true;
}
delay (0);
}
}
| 2be090ded344acee9b1c0ee7925260c5d5f0e41d | [
"C++"
] | 1 | C++ | SangNong/arduino-test | 312d6b38c6c770b7b7a8e11b2597e8f1c5f8f68f | f889a67caaaa7ad192f17a6c3830cfbb14506b56 |
refs/heads/master | <repo_name>andybeak/xml-parsing-demo<file_sep>/readme.md
# Mitigating XXE
This project is an example of parsing XML and mitigating [XXE](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing).
## Running the code
The code as shipped does not have side-effects, but you should examine the source code before running it to make sure.
You can run it with the following command:
docker run --rm -v $(pwd):/code -w /code php:cli php index.php
## Applying the mitigation
The `index.php` file ships with line 3 as `$applyMitigation = false;`.
If you set this variable to `true` then the code will run `libxml_disable_entity_loader()` prior to verifying the XML against the DTD (see line 20).
The code will produce errors when the mitigation is applied.<file_sep>/index.php
<?php
$applyMitigation = false;
$xml = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>
XML;
try {
$doc = new DOMDocument();
if ($applyMitigation !== false) {
libxml_disable_entity_loader();
}
$doc->validateOnParse = true;
if (false === $doc->loadXML($xml)) {
throw new Exception("That XML string is not well-formed");
}
$foo = $doc->getElementsByTagName('foo');
foreach ($foo as $element) {
var_dump($element);
}
} catch (Exception $e) {
echo "That XML string is not well-formed";
} | 562ad7f033d7b234ec33d0cefdc3fdefd9821d5a | [
"Markdown",
"PHP"
] | 2 | Markdown | andybeak/xml-parsing-demo | 4b929f3d5965213abd6035a9b2d4a5b387972a1b | 7f556e52227997810a4b495cd1e76e65f2cd355c |
refs/heads/master | <repo_name>AdamAgoune/test-git<file_sep>/Js/script.js
function popUp () {
alert("Vous venez de me créditer de 20.000$, merci bien !")
}
function infoConsole() {
console.log ("Bien vu barbu")
}
function popUp2 () {
alert("BIENVENUE ICI IL N'Y AS ENCORE PAS GRAND CHOSES")
}
function popUp3() {
alert("WESH LA ZONE")
}
// let jeux = prompt("Quel est ton jeux préféré?") ;
//if (jeux.toLowerCase() =="wow") {
// console.log("Best jeux ever") ;
//} else if (jeux.toLowerCase() =="cs") {
// console.log("Pas mal");
//}
//else if(jeux.toLowerCase() == "lol") {
//console.log("Ouais ca passe");
// }
//else {
// console.log("T'es mort dans le game");
//}
//for (let level = 0; level <= 60 ; level++) {
// console.log(`Je suis niveaux : ${level}`) ;
//}
// console.log("Voila tous les élèves de la classe de cm2") ;
// let list = ["Joseph" , "Jesus", "Moise", "Pierre", "Jean", "Jacques","Paul", "Micheline" ,"Nasser" ,"Paul" , "Patrick", "Stephane", "Sacha"] ;
// list.forEach (function(apprenant) {
// console.log(apprenant) ;
//});
// let chiant = prompt("Hey, on peux aller à Disneyland stp ?") ;
//while (chiant != "oui") {
// chiant = prompt("Aller stp stp stp") ;
//}
//console.log("Super !!")
//let title = document.querySelectorAll("p")[0];
//let liste = document.querySelectorAll("li")[5];
//let myH1 = document.querySelectorAll("h1")[2] ;
//document.querySelectorAll("li")[6].style.color.setProperty("color","red") ;
//document.querySelectorAll("li")[6].style.color.removeProperty("color") ;
document.querySelector(".title").addEventListener("mouseover", function() {
document.querySelector(".title").classList.toggle("modified-title") ;
});
document.querySelector(".title").addEventListener("mouseout", function() {
document.querySelector(".title").classList.toggle("modified-title") ;
});
document.querySelector(".liste").addEventListener("mouseover", function() {
document.querySelector(".liste").classList.toggle("listemodified") ;
});
document.querySelector(".liste").addEventListener("mouseout", function() {
document.querySelector(".liste").classList.toggle("listemodified")
});
document.querySelector(".balise1").addEventListener("click", function() {
document.getElementById("p1").classList.toggle("modified");
});
document.querySelector(".balise2").addEventListener("click", function() {
document.getElementById("p2").classList.toggle("modified");
});
document.querySelector(".color").addEventListener("click", function() {
document.querySelector("body").classList.toggle("bodymodified");
});
| a4199113def2c70e1e65934511f2a798caa3051d | [
"JavaScript"
] | 1 | JavaScript | AdamAgoune/test-git | 992e81890725f454ae072989478810631793acbf | 616525946f42188f2a6334ea6e9d8ec8d78703a4 |
refs/heads/master | <repo_name>Fencer04/maplistpro-geocoding<file_sep>/maplistpro-geocoding.php
<?php
/*
Plugin Name: Map List Pro Geocoding
Plugin URI: https://github.com/Fencer04/maplistpro-geocoding
Description: This plugin will geocode the items that have been imported or entered using the MapListPro Plugin.
Version: 1.0
Author: <NAME>
Author URI: http://justin-hansen.com
License: GPL2
*/
//Add Admin Menu Items and Settings Page
add_action( 'admin_menu', 'mlpg_setup_menu' );
function mlpg_setup_menu(){
add_submenu_page( 'edit.php?post_type=maplist', 'Map List Pro Geocoding', 'Geocoding', 'manage_options', 'geocoding', 'mlpg_geocoding_page' );
add_submenu_page( 'edit.php?post_type=maplist', 'Map List Pro Geocoding Settings', 'Geocoding Settings', 'manage_options', 'geocoding-options', 'mlpg_geocoding_options_page' );
add_action( 'admin_init', 'mlpg_register_mysettings' );
}
//Geocodeing settings page
function mlpg_register_mysettings() { // whitelist options
register_setting( 'mlpg-option-group', 'mlpg-api-key' );
}
//
function mlpg_geocoding_options_page(){?>
<div class="wrap">
<h2>Map List Pro Geocoding Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'mlpg-option-group' );
do_settings_sections( 'mlpg-option-group' );?>
<table class="form-table">
<tr valign="top">
<th scope="row">Google Geocoding API Key</th>
<td><input type="text" name="mlpg-api-key" style="width: 350px;" value="<?php echo esc_attr( get_option('mlpg-api-key') ); ?>" /><br />See <a href="https://developers.google.com/maps/documentation/geocoding/intro" target="_blank">Google Geocoding API</a> to get your own key.</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div><?php
}
//Geocoding User Interface
function mlpg_geocoding_page(){?>
<h1>Map List Pro Geocoding</h1>
<p>Select your options and click the button to see how many items there are to geocode. In order for this to work the locations must have correct street addresses listed in their address field. The free Google Maps API only allows 2500 location requests per day.</p>
<div id="countCheckArea">
<input type="radio" name="locationRadio" value="all" /><label for="locationRadio">Geocode all map locations</label><br />
<input type="radio" name="locationRadio" value="blank" checked="checked" /><label for="locationRadio">Geocode map locations without coordinates</label><br /><br />
<input type="button" name="checkGeo" id="checkGeo" value="Check Amount to Geocode" />
</div>
<div id="countArea"></div>
<div id="msgArea"></div>
<div id="errorArea" style="display: none;"></div>
<?php
}
//Add Javascript for geocoding to admin footer
add_action( 'admin_footer', 'mlpg_add_admin_javascript' );
function mlpg_add_admin_javascript(){
//blockUI
wp_enqueue_script( 'blockUI', plugins_url( '/js/jquery.blockUI.js', __FILE__ ), array(), '2.70.0', true );
//Main plugin javascript
wp_enqueue_script( 'maplistpro-geocode', plugins_url( '/js/main.js', __FILE__ ), array(), '1.0', true );
}
//Add Javascript to main site footer
add_action( 'wp_enqueue_scripts', 'mlpg_add_site_javascript' );
function mlpg_add_site_javascript(){
//Category override javascript
//wp_enqueue_script( 'maplistpro-category-override', plugins_url( '/js/category-override.js', __FILE__ ), array(), '1.0', true );
}
//AJAX Functions
//Get count for geocode
add_action( 'wp_ajax_mlpg_geocode_count', 'mlpg_geocode_count' );
function mlpg_geocode_count(){
$type = $_POST['type'];
$args = array('post_type' => 'maplist', 'posts_per_page' => -1);
//Check to see which locations will be geocoded
if($type == "blank"){
$meta_query = array(
'relation' => 'OR',
array( 'key' => 'maplist_latitude', 'value' => '' ),
array( 'key' => 'maplist_longitude', 'value' => '' )
);
$args['meta_query'] = $meta_query;
}
$locationList = new WP_Query( $args );
$locationInfo = array();
$locationResponse = array();
$locationResponse['count'] = $locationList->found_posts;
if($locationList->have_posts()) :
while( $locationList->have_posts() ) : $locationList->the_post();
$currentLocation = array('id' => get_the_ID(), 'name' => get_the_title(), 'address' => get_post_meta( get_the_ID(), 'maplist_address' )[0]);
$locationInfo[] = $currentLocation;
endwhile;
$locationResponse['locations'] = $locationInfo;
endif;
wp_send_json( $locationResponse );
wp_die();
}
//Geocode addresses
add_action( 'wp_ajax_mlpg_geocode', 'mlpg_geocode' );
function mlpg_geocode(){
//Grab API key from plugin settings page
$mapKey = get_option('mlpg-api-key');
$apiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
$address = urlencode($_POST['address']);
$curlUrl = $apiUrl . "?address=" . $address . "&key=" . $mapKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$location = json_decode(curl_exec($ch), true);
$curlError = curl_error();
curl_close();
$status = $location['status'];
if($status == "OK"){
$latitude = $location['results'][0]['geometry']['location']['lat'];
$longitude = $location['results'][0]['geometry']['location']['lng'];
//Update MapListPro item with results of geocoding
update_post_meta( $_POST['id'], 'maplist_latitude', $latitude );
update_post_meta( $_POST['id'], 'maplist_longitude', $longitude );
}
echo $status;
wp_die();
}
//Geocode single address
add_action( 'wp_ajax_mlpg_single_geocode', 'mlpg_single_geocode' );
function mlpg_single_geocode(){
//Grab API key from plugin settings page
$mapKey = get_option('mlpg-api-key');
$apiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
$address = urlencode($_POST['address']);
$curlUrl = $apiUrl . "?address=" . $address . "&key=" . $mapKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$location = json_decode(curl_exec($ch), true);
$curlError = curl_error();
curl_close();
$status = $location['status'];
$latitude = $location['results'][0]['geometry']['location']['lat'];
$longitude = $location['results'][0]['geometry']['location']['lng'];
$returnArray = array('status' => $status, 'latitude' => $latitude, 'longitude' => $longitude);
echo json_encode($returnArray);
wp_die();
}<file_sep>/README.md
# Map List Pro Geocoding
Wordpress plugin that adds geocoding capabilities to Map List Pro (http://codecanyon.net/item/map-list-pro-google-maps-location-directories/2620196)
Adds "Geocoding" and "Geocoding Settings" menu items to Map List Pro menu.
-- Geocodoing: Select to geocode all locations or just those without coordinates. Shows any errors with links to repair locations data and then resubmit items with errors for geocoding. Runs over asynchronously so the only limit on number of locations is Google's geocoding request limit.
-- Geocoding Settings: Place to enter the Google Geocoding API Key that can be obtained at https://developers.google.com/maps/documentation/geocoding/intro
| 649438d5a5b205c16eab2387c9da06b4be351dbd | [
"Markdown",
"PHP"
] | 2 | PHP | Fencer04/maplistpro-geocoding | 6d4ecfac7b2182cfc9bc971509a1ffa643811144 | 1ecab26e77fecf3bafd88cbc4c643fb8fcc575b9 |
refs/heads/master | <file_sep>import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
return (
<div className="App">
<div id="mainBox">
<h1>어플리케이션을 골라주세요</h1>
<span class="selectMenu" id="selectTodo">
TODO
</span>
{/* {온클릭 넣으면 해당페이지로 넘기기, 이름을 TODO로 바꾸고 TODO.js파일만들어서 리액트로 만들기, onclick={todo로가기}넣기} */}
<span class="selectMenu" id="selectBoard">
게시판
</span>
{/* {온클릭 넣으면 해당페이지로 넘기기, 이름을 Board로 바꾸고 Board.js파일만들어서 리액트로 만들기, onclick={Board로가기}} */}
</div>
</div>
);
}
export default App;
| d92aee2bef817d619f3ca3ee368735e6713a5525 | [
"JavaScript"
] | 1 | JavaScript | jch9537/HA2 | 9d9f9de0465350aefc69ec7bdab323691649fbcf | a024dd861d3fe4b55873fa2b2ef02d095ec656e6 |
refs/heads/master | <file_sep>class Hostname < ActiveRecord::Base
belongs_to :site
attr_accessible :hostname, :created_at, :updated_at, :site_id
end
<file_sep>require 'spec_helper'
require File.expand_path('../../factories', __FILE__)
describe Site do
describe 'find sites by hostname' do
Factory.build(:site).save
puts Site.find_by_hostname('example.com')
end
end
<file_sep>require 'spec_helper'
describe Hostname do
it 'initializes' do
Hostname.new.should_not be_nil
end
describe "hostname" do
it {should allow_value('localhost').for(:hostname)}
end
describe "find host example.com" do
it 'find saved hostname' do
Factory.build(:hostname, :hostname=>'example.com').save
Hostname.find_by_hostname('example.com').should_not be_nil
end
end
end
<file_sep>Factory.define :post do |f|
f.title 'Post title'
end
Factory.define :hostname do |f|
f.hostname 'example.com'
end
Factory.define :site do |f|
f.name 'ex'
f.hostnames {|site| [site.association(:hostname),
site.association(:hostname, :hostname=>'test.host')]}
end<file_sep># -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "refinerycms-multisite/version"
Gem::Specification.new do |s|
s.name = "refinerycms-multisite"
s.version = Refinerycms::Multisite::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = ""
s.summary = %q{Multisite-Plugin for Refinery-CMS}
s.description = %q{Manage multiple Site with Refinery-CMS}
s.rubyforge_project = "refinerycms-multisite"
s.add_dependency "refinerycms-pages"
s.add_development_dependency "refinerycms-testing"
s.add_development_dependency "shoulda-matchers"
s.files = `git ls-files | grep -v ^script`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
end
<file_sep>class ::Refinery::Admin::SitesController < Admin::BaseController
skip_filter :load_site
#Not namespacing the site model because the purpose is to enable an app-specific site model that
#might not be exclusive to refinery.
crudify :site,
:title_attribute => :name,
:order => "name ASC",
#:redirect_to_url => :redirect_to_where?,
:xhr_paging => true
end
<file_sep>require 'spec_helper'
describe Admin::SitesController do
include Devise::TestHelpers
before(:each) do
sign_in Factory.create(:refinery_user)
@origin_site=Factory.create(:site)
@origin_site.save
end
context 'GET on new' do
before(:each) { get :new }
it('assigns a new site') { assigns(:site).should be_a_new(Site) }
it('responds with success') { response.should be_success }
end
context 'POST on create' do
before(:each) { post :create, :post => Factory.attributes_for(:site) }
it('responds with a redirect') do
response.should redirect_to(:action=>:index)
end
it('creates a new site') { assigns(:site).should_not be_a_new_record }
end
context 'persisted site' do
let(:site) { Factory(:site) }
context 'GET on edit' do
before(:each) { get :edit, :id => site }
it('response with success') { response.should be_success }
end
context 'GET on index' do
before(:each) { get :index }
it('response with success') { response.should be_success}
it('assigns sites') do
assigns(:sites).should include(@origin_site)
end
end
end
end
<file_sep>::Refinery::Application.routes.draw do
scope(:path => 'refinery', :as => 'refinery_admin', :module => 'refinery/admin') do
resources :sites do
resources :hostnames
end
end
end
<file_sep>#!/bin/bash
PROJECTZERO=git://github.com/panter/project_zero.git
cd "$(dirname "$0")/.."
CURRENTPROJECT="$(pwd)"
mkdir tmp
cd tmp
rm -rf rickrockstar
git clone "$PROJECTZERO" rickrockstar
cd rickrockstar
rvm gemset clear
echo "gem 'refinerycms-multisite', :git=>'file://$CURRENTPROJECT'">>Gemfile
. script/init_refinery Rickrockstar
patch -p0 <"$CURRENTPROJECT/spec/Patch_projectzero_for_working_with_refinerycms.patch"
rake spec<file_sep>Simple Multisite-Plugin for refinery-cms
========================================
## Idea
With this Plugin you can have Multiple Site in one Refinery-Instance by
switching the Menu-Tree and the Style-Sheet based on the hostname.
## Integrate in your own Refinery Project
Add following line to your Gemfile:
gem "refinerycms-multisite"
And update your Project by executing the following commands
bundle
rails g refinerycms_multisite
rake db:migrate
### Stylesheet
Write your site-specific stylesheet to public/stylesheets.
### Entring Site-Data
Go to the Page `refinery/sites` and add a Start-Site. You have to select the
Root-Page and enter the stylesheet-name and all valid hostnames for this site.
## How to test
call script/test.sh<file_sep>require 'refinerycms-base'
module Refinery
module Sites
class Engine < Rails::Engine
class << self
attr_accessor :root
def root
@root ||= Pathname.new(File.expand_path('../../', __FILE__))
end
end
class Engine < ::Rails::Engine
isolate_namespace ::Refinery
initializer "init plugin", :after => :set_routes_reloader do |app|
::Refinery::Plugin.register do |plugin|
plugin.pathname = root
plugin.name = 'refinery_sites'
plugin.url = app.routes.url_helpers.refinery_admin_sites_path
plugin.version = Refinerycms::Multisite::VERSION
plugin.menu_match = /refinery\/sites$/
end
end
end
end
end
module SiteModel
extend ActiveSupport::Concern
included do
belongs_to :page
attr_accessible :name, :page_id, :stylesheet, :hostnames,
:hostnames_attributes
has_many :hostnames, :dependent => :destroy
accepts_nested_attributes_for :hostnames, :allow_destroy => true
end
module ClassMethods
def find_by_hostname(hostname)
Site.joins(:hostnames).where(:hostnames=>{:hostname=>hostname}).first ||
Site.joins(:hostnames).where(:hostnames=>{:hostname=>'*'}).first
end
end
module InstanceMethods
end
end
module SiteModelClassMethods
#include ActiveRecord
end
end
module PagesControllerSite
def home_with_site
if (@site)
@page = Page.find(@site.page_id)
if @page.try(:live?) || (refinery_user? && current_user.authorized_plugins.include?("refinery_pages"))
# if the admin wants this to be a "placeholder" page which goes to its first child, go to that instead.
if @page.skip_to_first_child && (first_live_child = @page.children.order('lft ASC').live.first).present?
redirect_to first_live_child.url
elsif @page.link_url.present?
redirect_to @page.link_url and return
end
else
error_404
end
else
home_without_site
end
end
end
class ActionController::Base
# Loading the Current Site
before_filter :load_site
protected
def load_site
@site = Site.find_by_hostname(request.host)
return if Refinery::PagesController.include? PagesControllerSite
# Monkey-Patch the Page-Controller for loading the right root-Page
Refinery::PagesController.class_eval do
include PagesControllerSite
alias_method_chain :home, :site
end
end
end
<file_sep>class Site < ActiveRecord::Base
include Refinery::SiteModel
end
<file_sep>require 'spec_helper'
describe "FactoryGirl" do
describe "a hostname by factory" do
let(:hostname){Factory.build(:hostname)}
it{hostname.should be_valid}
end
describe "a sites by factory" do
let(:site){Factory.build(:site)}
it{site.should be_valid}
end
end
| 1f57a40a851acf4791de827a5984166fcfb7770f | [
"Markdown",
"Ruby",
"Shell"
] | 13 | Ruby | YuzuTen/refinerycms-multisite | ec38fa1890c7a4edd34a9af612b5c61a870441c6 | f05dee1c6ff7f897146c5779046f3c44d5ac68d9 |
refs/heads/master | <repo_name>benlturner/EECS-493-Final-Project<file_sep>/README.txt
MAIZE INVADERS v1.0
----------------
This code is the basis for a simple 'space invaders' game.
In order to run the game, open up index.html in the web browser of
your choice, preferably google chrome.
After you have opened the game in your web browser, follow the instructions
on screen to play the game.
To close the game, close the tab in your web browser.
-----------------<file_sep>/README.md
# EECS-493-Final-Project
Final project for EECS 493
<file_sep>/scripts/page.js
//// Page-scoped globals ////
var cr_prj_id; // global projectile counter variable
// global becsause it's reset in mutliple scope-d functions
// we need a better comment or at least name than this
// Counters
var snowballIdx = 1;
var projectileIdx = 1;
var enemyIdx = 1;
var bunkerIdx = 1;
var itemIdx = 1;
// Game Constants
var OBJECT_REFRESH_RATE = 50; // ms
var ENEMY_DOUBLE_RATIO = 0.5;
var PROJECTILE_SIZE = 40;
var PROJECTILE_SPEED = 5;
var SCORE_UNIT_PROJECTILE = 5;
var SCORE_UNIT_HIT = 50;
var SCORE_UNIT_KILL = 100;
var SNOWMAN_SPEED = 25;
var SNOWBALL_SPEED = 10;
var BUNKERSIZE = 100;
var ITEMSIZE = 100;
// Movement Restrictions
var maxSnowmanPosX, maxSnowmanPosY, maxEnemyPosX;
// Player Shop-affected vars
var SNOWBALL_SIZE = 20;
var SNOWBALL_RECHARGE = 400;
var NUM_EQUIPPED = 0;
var NUM_SNOWBALLS = 1;
var SNOWBALL_DURABILITY = 1;
var GHOST_SNOWBALL = false;
// Gamestate vars
var ENEMY_DIRECTION = "right";
var ENEMY_SPEED = 2;
var SNOWBALL_TIMER = 0;
var KEYARRAY = [false, false, false];
var CUR_LEVEL = 0;
var GAME_PAUSED = false;
var GAME_OVER = false;
var GAME_COMPLETE = false;
var GAME_CONTINUE = false;
var IN_STORE = false;
var PROJECTILES_FALLING = false;
// Global Window Handles (gwh__) --> replaced with Vue.js
var gwhGame, gwhOver, gwhStatus, gwhObjectives, gwhControls;
// Global Object Handles
var snowman;
// Level Data
var ENEMY_PATTERN = [[7,1],[10,1],[6,2],[15,1],[8,1],[5,3],[10,1],[7,2],[8,3],[10,2],[10,3]]; // Enemies Wide, Enemies Deep
var PROJECTILE_SPAWN_RATE = [1400,1200,1300,800,700,1100,700,1400,1000,700,1000]; // ms
var NUM_BUNKERS = [4,3,5,4,5,3,2,4,2,1,0];
var LEVEL_SPEED = [2,1.8,2.5,2,4,1.2,3,2,1.1,2.5,2]; // Enemy Horizontal Speed
var ENEMY_DESCENT_SPEED = [0.25,0.4,0.3,0.25,0.8,0.3,0.4,0.25,0.2,0.4,0.3] // Enemy Vertical Speed
const NUM_LEVELS = ENEMY_PATTERN.length;
// Current Level Vars
var threshold = Math.ceil(ENEMY_DOUBLE_RATIO * ENEMY_PATTERN[CUR_LEVEL][0] * ENEMY_PATTERN[CUR_LEVEL][1]);
var NUM_ENEMIES = ENEMY_PATTERN[CUR_LEVEL][1] * ENEMY_PATTERN[CUR_LEVEL][0]
var ENEMY_SIZE = Math.min(100, 100 * 8 / (ENEMY_PATTERN[CUR_LEVEL][0] + 1));
var KEYS = {
enter : 13,
left : 37,
right : 39,
spacebar: 32,
r : 82
}
//// Functional Code ////
// Main
$(document).ready( function() {
// Now that the elements have loaded, populate with Vue.js
createVueObjects();
console.log("Ready!");
// Set global handles (now that the page is loaded)
gwhGame = $('.game-window');
gwhOver = $('.game-over');
gwhStatus = $('.status-window');
gwhObjectives = $('.objectives');
gwhControls = $('.controls');
gwhStore = $('.store');
gwhStoreItems = $('.items');
snowman = $('#enterprise'); // set the global snowman handle
// Set global positions
maxSnowmanPosX = gwhGame.width() - 50;
maxSnowmanPosY = gwhGame.height() - 70;
SNOWMAN_OBJ.snowmanStyle.top = maxSnowmanPosY;
gwhGame.hide();
$(window).keydown(keydownRouter);
$(window).keyup(keyupRouter);
// show titlescreen first
setTimeout (function () {
// show objectives
$('#titleScreen').hide();
gwhObjectives.show();
setTimeout (function () {
// show controls
gwhObjectives.hide();
gwhControls.show();
setTimeout(function () {
// show level screen
$('#levelScreen').show();
gwhControls.hide();
setTimeout(function () {
gwhControls.hide();
$('#levelScreen').hide();
gwhGame.show();
gwhStatus.show();
setupIntervals();
}, 5000);
}, 10000);
}, 10000);
}, 5000);
});
// set up all the intervals and the game
function setupIntervals() {
// Periodically check for collisions (instead of checking every position-update)
let ch_co_id = setInterval( function() {
checkCollisions(); // Remove elements if there are collisions
}, 100);
// Update Snowball reload
let rl_sb_id = setInterval (function() {
SNOWBALL_TIMER = SNOWBALL_TIMER + 100;
},100);
// Create enemies
maxEnemyPosX = gwhGame.width() - ENEMY_SIZE + 10;
createEnemies(ENEMY_SIZE);
createBunkers();
if (!PROJECTILES_FALLING) {
cr_prj_id = setInterval(function() {
createProjectile();
}, PROJECTILE_SPAWN_RATE[CUR_LEVEL]);
PROJECTILES_FALLING = true;
}
// Move enemies
let mv_en_id = setInterval ( function() {
moveEnemies();
if (NUM_ENEMIES === 0 && GAME_COMPLETE === false) {
clearInterval(cr_prj_id);
PROJECTILES_FALLING = false;
newLevel();
}
if (GAME_COMPLETE) {
// Remove all game elements
$('.snowball').remove();
$('.projectile').remove();
$('.enemy').remove();
clearInterval(cr_prj_id);
PROJECTILES_FALLING = false;
// Hide primary windows
gwhGame.hide();
$('#winner').show();
}
else if (GAME_OVER) {
// Remove all game elements
$('.snowball').remove();
$('.projectile').remove();
$('.enemy').remove();
clearInterval(cr_prj_id);
PROJECTILES_FALLING = false;
// Hide primary windows
gwhGame.hide();
// Show "Game Over" screen
gwhOver.show();
}
}, 100);
}
// Handles enemy creation
function createEnemies(ENEMY_SIZE) {
var enemyOffset = 1.1*ENEMY_SIZE;
var i;
for (i = 0; i < ENEMY_PATTERN[CUR_LEVEL][0]; i++) {
var j;
for (j = 0; j < ENEMY_PATTERN[CUR_LEVEL][1]; j++) {
var enemyDivStr = "<div id='e-" + enemyIdx + "' class='enemy'></div>"
gwhGame.append(enemyDivStr);
var $curEnemy = $('#e-'+enemyIdx);
$curEnemy.css('position',"absolute");
$curEnemy.css('left', (5 + (i * enemyOffset)) + "px");
$curEnemy.css('top', (15 + (j * enemyOffset)) + "px");
$curEnemy.css('width', ENEMY_SIZE + "px");
$curEnemy.css('height', ENEMY_SIZE + "px");
$curEnemy.append("<img src='img/snowman.png' height ='" + ENEMY_SIZE + " width =" + ENEMY_SIZE + "'/>");
$curEnemy.children('img').attr('position', 'absolute');
enemyIdx++;
}
}
}
function createBunkers() {
var bunkerSpacing = Math.floor((900 - (NUM_BUNKERS[CUR_LEVEL] * BUNKERSIZE)) / ((NUM_BUNKERS[CUR_LEVEL] + 1)));
var i;
for (i = 0; i < NUM_BUNKERS[CUR_LEVEL]; i++) {
var bunkerDivStr = "<div id='b-" + bunkerIdx + "' class='bunker'></div>"
gwhGame.append(bunkerDivStr);
var $curBunker = $('#b-'+bunkerIdx);
$curBunker.css('position',"absolute");
$curBunker.css('left', ((bunkerSpacing) + (i * (BUNKERSIZE + bunkerSpacing))) + "px");
$curBunker.css('top', ((parseInt(gwhGame.height()) - 200) + "px"));
$curBunker.css('width', "112 px");
$curBunker.css('height', "112 px");
$curBunker.append("<img src='img/gift.png' height = " + BUNKERSIZE + " px width = " + BUNKERSIZE + " px'/>");
$curBunker.children('img').attr('position', 'absolute');
bunkerIdx++;
}
}
function keydownRouter(e) {
switch (e.which) {
case KEYS.r: {
if (GAME_OVER) {
restartGame();
}
break;
}
case KEYS.enter: {
if (GAME_COMPLETE) {
continueGame();
}
break;
}
case KEYS.spacebar: {
KEYARRAY[0] = true;
break;
}
case KEYS.left: {
KEYARRAY[1] = true;
break;
}
case KEYS.right: {
KEYARRAY[2] = true;
break;
}
default:
console.log("Invalid input!");
}
switch (KEYARRAY.join(' ')) {
case 'false false true': {
moveSnowman(KEYS.right);
break;
}
case 'true false true': {
moveSnowman(KEYS.right);
if (SNOWBALL_TIMER > SNOWBALL_RECHARGE) {
fire();
}
break;
}
case 'true false false': {
if (SNOWBALL_TIMER > SNOWBALL_RECHARGE) {
fire();
}
break;
}
case 'true true false': {
moveSnowman(KEYS.left);
if (SNOWBALL_TIMER > SNOWBALL_RECHARGE) {
fire();
}
break;
}
case 'false true false': {
moveSnowman(KEYS.left);
break;
}
default: {
}
}
e.Handled = true;
}
function keyupRouter(e) {
switch (e.which) {
case KEYS.spacebar: {
KEYARRAY[0] = false;
break;
}
case KEYS.left: {
KEYARRAY[1] = false;
break;
}
case KEYS.right: {
KEYARRAY[2] = false;
}
}
}
function fire() {
switch (NUM_SNOWBALLS) {
case 1: {
fireSnowball();
break;
}
case 2: {
fire_double_snowball();
break;
}
case 3: {
fire_triple_snowball();
break;
}
}
}
// Handle "fire" [snowball] events
function fireSnowball() {
if(!GAME_PAUSED){
var snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball = $('#r-'+snowballIdx);
let curImg = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
curSnowball.css('top', SNOWMAN_OBJ.snowmanStyle.top);
var rxPos = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4; // In order to center the snowball, shift by half the div size (recall: origin [0,0] is top-left of div)
curSnowball.css('left', rxPos+"px");
curSnowball.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball.css('height', SNOWBALL_SIZE + "px");
curSnowball.css('width', SNOWBALL_SIZE + "px");
curImg.css('height', SNOWBALL_SIZE + "px");
curImg.css('width', SNOWBALL_SIZE + "px");
// Create movement update handler
setInterval( function() {
curSnowball.css('top', parseInt(curSnowball.css('top'))-SNOWBALL_SPEED);
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball.css('top')) < 0) {
//curSnowball.hide();
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
SNOWBALL_TIMER = 0;
}
}
function fire_double_snowball() {
if(!GAME_PAUSED){
//make the first snowball
var snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball = $('#r-'+snowballIdx);
let curImg = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
// make the second snowball
var snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball2 = $('#r-'+snowballIdx);
let curImg2 = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
curSnowball.css('top', SNOWMAN_OBJ.snowmanStyle.top);
curSnowball2.css('top', SNOWMAN_OBJ.snowmanStyle.top);
var rxPos = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4 + SNOWBALL_SIZE/2;
var rxPos2 = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4 - SNOWBALL_SIZE/2;
curSnowball.css('left', rxPos+"px");
curSnowball2.css('left', rxPos2+"px");
curSnowball.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball2.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball.css('height', SNOWBALL_SIZE + "px");
curSnowball2.css('height', SNOWBALL_SIZE + "px");
curSnowball.css('width', SNOWBALL_SIZE + "px");
curSnowball2.css('width', SNOWBALL_SIZE + "px");
curImg.css('height', SNOWBALL_SIZE + "px");
curImg2.css('height', SNOWBALL_SIZE + "px");
curImg.css('width', SNOWBALL_SIZE + "px");
curImg2.css('width', SNOWBALL_SIZE + "px");
// Create movement update handler
setInterval( function() {
curSnowball.css('top', parseInt(curSnowball.css('top'))-SNOWBALL_SPEED);
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball.css('top')) < 0) {
//curSnowball.hide();
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
setInterval( function() {
curSnowball2.css('top', parseInt(curSnowball2.css('top'))-SNOWBALL_SPEED);
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball2.css('top')) < 0) {
//curSnowball.hide();
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
SNOWBALL_TIMER = 0;
}
}
function fire_triple_snowball() {
if(!GAME_PAUSED){
//make the first snowball
var snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball = $('#r-'+snowballIdx);
let curImg = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
// make the second snowball
snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball2 = $('#r-'+snowballIdx);
let curImg2 = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
// make the third snowball
snowballDivStr = "<div id='r-" + snowballIdx + "' class='snowball'><img src='img/snowball.png'/></div>";
// Add the snowball to the screen
gwhGame.append(snowballDivStr);
// Create and snowball handle based on newest index
var curSnowball3 = $('#r-'+snowballIdx);
let curImg3 = $('#r-'+snowballIdx + ' img');
snowballIdx++; // update the index to maintain uniqueness next time
curSnowball.css('top', SNOWMAN_OBJ.snowmanStyle.top);
curSnowball2.css('top', SNOWMAN_OBJ.snowmanStyle.top);
curSnowball3.css('top', SNOWMAN_OBJ.snowmanStyle.top);
var rxPos = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4 + SNOWBALL_SIZE;
var rxPos2 = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4 - SNOWBALL_SIZE/2;
var rxPos3 = SNOWMAN_OBJ.snowmanStyle.left + snowman.width()/4 + SNOWBALL_SIZE/4;
curSnowball.css('left', rxPos+"px");
curSnowball2.css('left', rxPos2+"px");
curSnowball3.css('left', rxPos3+"px");
curSnowball.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball2.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball3.css('fontSize', SNOWBALL_DURABILITY * 10);
curSnowball.css('height', SNOWBALL_SIZE + "px");
curSnowball2.css('height', SNOWBALL_SIZE + "px");
curSnowball3.css('height', SNOWBALL_SIZE + "px");
curSnowball.css('width', SNOWBALL_SIZE + "px");
curSnowball2.css('width', SNOWBALL_SIZE + "px");
curSnowball3.css('width', SNOWBALL_SIZE + "px");
curImg.css('height', SNOWBALL_SIZE + "px");
curImg2.css('height', SNOWBALL_SIZE + "px");
curImg3.css('height', SNOWBALL_SIZE + "px");
curImg.css('width', SNOWBALL_SIZE + "px");
curImg2.css('width', SNOWBALL_SIZE + "px");
curImg3.css('width', SNOWBALL_SIZE + "px");
// Create movement update handler
setInterval( function() {
curSnowball.css('top', parseInt(curSnowball.css('top'))-SNOWBALL_SPEED);
if (parseInt(curSnowball.css('left')) + SNOWBALL_SIZE < 900) {
curSnowball.css('left', parseInt(curSnowball.css('left'))+SNOWBALL_SPEED/8);
}
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball.css('top')) < 0) {
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
setInterval( function() {
curSnowball2.css('top', parseInt(curSnowball2.css('top'))-SNOWBALL_SPEED);
curSnowball2.css('left', parseInt(curSnowball2.css('left')) - SNOWBALL_SPEED/16);
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball2.css('top')) < 0) {
//curSnowball.hide();
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
SNOWBALL_TIMER = 0;
setInterval( function() {
curSnowball3.css('top', parseInt(curSnowball3.css('top'))-SNOWBALL_SPEED);
// Check to see if the snowball has left the game/viewing window
if (parseInt(curSnowball3.css('top')) < 0) {
//curSnowball.hide();
curSnowball.remove();
}
}, OBJECT_REFRESH_RATE);
}
}
// Handle snowman movement events
function moveSnowman(arrow) {
if(!GAME_PAUSED){
switch (arrow) {
case KEYS.left: // left arrow
SNOWMAN_OBJ.snowmanStyle.left = Math.max(15, SNOWMAN_OBJ.snowmanStyle.left - SNOWMAN_SPEED);
break;
case KEYS.right: // right arrow
SNOWMAN_OBJ.snowmanStyle.left = Math.min(maxSnowmanPosX, SNOWMAN_OBJ.snowmanStyle.left + SNOWMAN_SPEED);
break;
}
}
}
//Handles enemy movement
function moveEnemies() {
if(!GAME_PAUSED){
if (ENEMY_DIRECTION === "left") {
$('.enemy').each( function() {
var $curEnemy = $(this);
if ((parseInt($curEnemy.css('left')) - ENEMY_SPEED) < 5) {
ENEMY_DIRECTION = "right";
$('.enemy').each( function() {
var $curEnemy = $(this);
$curEnemy.css('top', parseInt($curEnemy.css('top')) + (ENEMY_SIZE * ENEMY_DESCENT_SPEED[CUR_LEVEL]));
if (parseInt($curEnemy.css('top')) > 450) {
GAME_OVER = true;
GAME_PAUSED = true;
}
});
return false;
}
});
if (ENEMY_DIRECTION === "left") {
$('.enemy').each( function() {
var $curEnemy = $(this);
$curEnemy.css('left', parseInt($curEnemy.css('left')) - ENEMY_SPEED)
});
}
}
else {
$('.enemy').each( function() {
var $curEnemy = $(this);
if ((parseInt($curEnemy.css('left')) + ENEMY_SPEED) > maxEnemyPosX) {
ENEMY_DIRECTION = "left";
$('.enemy').each( function() {
var $curEnemy = $(this);
$curEnemy.css('top', parseInt($curEnemy.css('top')) + (ENEMY_SIZE * ENEMY_DESCENT_SPEED[CUR_LEVEL]));
if (parseInt($curEnemy.css('top')) > 450) {
GAME_OVER = true;
GAME_PAUSED = true;
}
});
return false;
}
});
if (ENEMY_DIRECTION === "right") {
$('.enemy').each( function() {
var $curEnemy = $(this);
$curEnemy.css('left', parseInt($curEnemy.css('left')) + ENEMY_SPEED)
});
}
}
if (NUM_ENEMIES < threshold) {
ENEMY_SPEED = ENEMY_SPEED*2;
threshold = Math.ceil(threshold*ENEMY_DOUBLE_RATIO);
}
}
}
// Handle projectile creation events
function createProjectile() {
if (!GAME_PAUSED){
var projectileDivStr = "<div id='a-" + projectileIdx + "' class='projectile'></div>"
// Add the snowball to the screen
gwhGame.append(projectileDivStr);
// Create and projectile handle based on newest index
var $curProjectile = $('#a-'+projectileIdx);
projectileIdx++; // update the index to maintain uniqueness next time
var projectileEnemyID = Math.floor(Math.random() * NUM_ENEMIES);
$curProjectile.css('width', PROJECTILE_SIZE+"px");
$curProjectile.css('height', PROJECTILE_SIZE+"px");
if(Math.random() < 1/3){
$curProjectile.append("<img src='img/blueBook.png' height='" + PROJECTILE_SIZE + "'/>")
} else if(Math.random() < 2/3) {
$curProjectile.append("<img src='img/icicle.png' height='" + PROJECTILE_SIZE + "'/>")
} else {
$curProjectile.append("<img src='img/glasses.png' height='" + PROJECTILE_SIZE + "'/>")
}
var index = 0
let startingPositionLeft;
let startingPositionBottom;
$('.enemy').each( function() {
var $curEnemy = $(this);
if(index === projectileEnemyID){
startingPositionLeft = parseInt($curEnemy.css('left')) + parseInt($curEnemy.css('width'))/2.5
startingPositionBottom = parseInt($curEnemy.css('top')) + parseInt($curEnemy.css('height'))
}
index++
});
$curProjectile.css('left', startingPositionLeft+"px");
$curProjectile.css('top', startingPositionBottom+"px");
// Make the projectiles fall towards the bottom
setInterval( function() {
$curProjectile.css('top', parseInt($curProjectile.css('top'))+PROJECTILE_SPEED);
// Check to see if the projectile has left the game/viewing window
if (parseInt($curProjectile.css('top')) > (gwhGame.height() - $curProjectile.height())) {
$curProjectile.remove();
}
}, OBJECT_REFRESH_RATE);
}
}
// Check for any collisions and update/remove the appropriate object if needed
function checkCollisions() {
if(!GAME_PAUSED){
// First, check for snow-ball projectile interactions
$('.snowball').each( function() {
var $curSnowball = $(this); // define a local handle for this rocket
$('.projectile').each( function() {
var $curProjectile = $(this); // define a local handle for this asteroid
if (isColliding($curSnowball, $curProjectile, 0)) {
if (parseInt($curSnowball.css('fontSize')) === 10) {
$curSnowball.remove();
}
else {
$curSnowball.css('fontSize', parseInt($curSnowball.css('fontSize')) - 10);
}
$curProjectile.remove();
SCORE_OBJ.score += SCORE_UNIT_PROJECTILE;
}
});
});
// Next, check for snowball-enemy interactions
$('.snowball').each( function() {
var $curSnowball = $(this); // define a local handle for this snowball
$('.enemy').each( function() {
var $curEnemy = $(this); // define a local handle for this enemy
off = 12
if ($curEnemy.children('img').attr('src') == 'img/snowman1ball.png'){
off = 25
}
// For each snowball and enemy, check for collisions
if (isColliding($curSnowball, $curEnemy, off)) {
// If a snowball and enemy collide, remove a ball from the enemy
switch ($curEnemy.children('img').attr('src')) {
case 'img/snowman.png': {
$curEnemy.children('img').attr('src', 'img/snowman2balls.png');
if (parseInt($curSnowball.css('fontSize')) === 10) {
$curSnowball.remove();
}
else {
$curSnowball.css('fontSize', parseInt($curSnowball.css('fontSize')) - 10);
}
$curEnemy.css('height', 60);
SCORE_OBJ.score += SCORE_UNIT_HIT;
break;
}
case 'img/snowman2balls.png': {
$curEnemy.children('img').attr('src', 'img/snowman1ball.png');
if (parseInt($curSnowball.css('fontSize')) === 10) {
$curSnowball.remove();
}
else {
$curSnowball.css('fontSize', parseInt($curSnowball.css('fontSize')) - 10);
}
$curEnemy.css('height', 30);
SCORE_OBJ.score += SCORE_UNIT_HIT;
break;
}
case 'img/snowman1ball.png': {
$curEnemy.remove();
if (parseInt($curSnowball.css('fontSize')) === 10) {
$curSnowball.remove();
}
else {
$curSnowball.css('fontSize', parseInt($curSnowball.css('fontSize')) - 10);
}
NUM_ENEMIES--;
SCORE_OBJ.score += SCORE_UNIT_KILL;
}
}
}
});
});
// Next, check for snowball-gift interactions
$('.snowball').each( function() {
var $curSnowball = $(this); // define a local handle for this snowball
$('.bunker').each( function() {
var $curBunker = $(this); // define a local handle for this enemy
if (isColliding($curSnowball, $curBunker, 10)) {
if (!GHOST_SNOWBALL) {
$curSnowball.remove();
}
}
});
});
// Next, check for projectile-gift interactions
$('.bunker').each( function() {
var $curBunker = $(this); // define a local handle for this rocket
$('.projectile').each( function() {
var $curProjectile = $(this); // define a local handle for this asteroid
// For each projectile and bunker, check for collisions
if (isColliding($curBunker, $curProjectile, 10)) {
// If a projectile and bunker collide, take a layer off the bunker
switch ($curBunker.children('img').attr('src')) {
case 'img/gift.png': {
$curBunker.children('img').attr('src', 'img/gift1.png');
$curProjectile.remove();
let bunkerHeight = parseInt($curBunker.css('height'));
break;
}
case 'img/gift1.png': {
$curBunker.children('img').attr('src', 'img/gift2.png');
$curProjectile.remove();
break;
}
case 'img/gift2.png': {
$curBunker.children('img').attr('src', 'img/gift3.png');
$curProjectile.remove();
break;
}
case 'img/gift3.png': {
$curBunker.children('img').attr('src', 'img/gift4.png');
$curProjectile.remove();
break;
}
case 'img/gift4.png': {
$curBunker.remove();
$curProjectile.remove();
}
}
}
});
});
// Next, check for enemy-snowman interactions
$('.enemy').each( function() {
var $curEnemy = $(this);
if (isColliding($curEnemy, snowman, 0)) {
GAME_OVER = true;
GAME_PAUSED = true;
}
});
// Next, check for projectile-snowman interactions
$('.projectile').each( function() {
var $curProjectile = $(this);
if (isColliding($curProjectile, snowman, 0)) {
LIVES_OBJ.lives -=1;
$curProjectile.remove();
if (LIVES_OBJ.lives === 0) {
GAME_OVER = true;
GAME_PAUSED = true;
}
}
});
}
}
// Check if two objects are colliding
function isColliding(o1, o2, offset) {
// Define input direction mappings for easier referencing
o1D = { 'left': parseInt(o1.css('left')),
'right': parseInt(o1.css('left')) + o1.width(),
'top': parseInt(o1.css('top')),
'bottom': parseInt(o1.css('top')) + o1.height()
};
o2D = { 'left': parseInt(o2.css('left')) + offset,
'right': parseInt(o2.css('left')) + o2.width() - offset,
'top': parseInt(o2.css('top')),
'bottom': parseInt(o2.css('top')) + o2.height()
};
// If horizontally overlapping...
if (o1D.left <= o2D.right &&
o1D.right >= o2D.left &&
o1D.top <= o2D.bottom &&
o1D.bottom >= o2D.top) {
// collision detected!
return true;
}
return false;
}
function newLevel(){
GAME_PAUSED = true;
console.log("proceeding to next level");
$('.snowball').remove();
$('.projectile').remove();
$('.bunker').remove();
CUR_LEVEL++
if (GAME_CONTINUE) {
LEVEL_OBJ.level += 1
$('#store').show();
$('#levelScreen').show();
gwhGame.hide();
ENEMY_SPEED = Math.random()*5 + 0.5;
ENEMY_DESCENT_SPEED[CUR_LEVEL] = Math.random()*0.4 + 0.1
ENEMY_PATTERN[CUR_LEVEL] = [Math.floor(Math.random()*17.5) + 3,Math.floor(Math.random()*2.99) + 1];
PROJECTILE_SPAWN_RATE[CUR_LEVEL] = Math.random()*1500 + 500;
threshold = Math.ceil(ENEMY_DOUBLE_RATIO * ENEMY_PATTERN[CUR_LEVEL][0] * ENEMY_PATTERN[CUR_LEVEL][1]);
NUM_ENEMIES = ENEMY_PATTERN[CUR_LEVEL][1] * ENEMY_PATTERN[CUR_LEVEL][0];
maxEnemyPosX += ENEMY_SIZE;
ENEMY_SIZE = Math.min(100, 100 * 8 / (ENEMY_PATTERN[CUR_LEVEL][0] + 1));
maxEnemyPosX -= ENEMY_SIZE;
NUM_BUNKERS[CUR_LEVEL] = Math.floor(Math.random()*5.5);
// check if store is opened
setTimeout(function() {
if (!IN_STORE) {
createEnemies(ENEMY_SIZE);
createBunkers();
if (!PROJECTILES_FALLING) {
cr_prj_id = setInterval(function() {
createProjectile();
}, PROJECTILE_SPAWN_RATE[CUR_LEVEL]);
PROJECTILES_FALLING = true;
}
$('#levelScreen').hide();
gwhGame.show();
GAME_PAUSED = false;
}
}, 7000)
}
else if (CUR_LEVEL < NUM_LEVELS) {
LEVEL_OBJ.level += 1
$('#store').show();
$('#levelScreen').show();
gwhGame.hide();
ENEMY_SPEED = LEVEL_SPEED[CUR_LEVEL];
threshold = Math.ceil(ENEMY_DOUBLE_RATIO * ENEMY_PATTERN[CUR_LEVEL][0] * ENEMY_PATTERN[CUR_LEVEL][1]);
NUM_ENEMIES = ENEMY_PATTERN[CUR_LEVEL][1] * ENEMY_PATTERN[CUR_LEVEL][0];
maxEnemyPosX += ENEMY_SIZE;
ENEMY_SIZE = Math.min(100, 100 * 8 / (ENEMY_PATTERN[CUR_LEVEL][0] + 1));
maxEnemyPosX -= ENEMY_SIZE;
// check if store is opened
setTimeout(function() {
if (!IN_STORE) {
createEnemies(ENEMY_SIZE);
createBunkers();
if (!PROJECTILES_FALLING) {
cr_prj_id = setInterval(function() {
createProjectile();
}, PROJECTILE_SPAWN_RATE[CUR_LEVEL]);
PROJECTILES_FALLING = true;
}
$('#levelScreen').hide();
gwhGame.show();
GAME_PAUSED = false;
}
}, 5000)
}
else {
GAME_COMPLETE = true;
GAME_OVER = true;
}
}
// opens the game store
function openStore() {
IN_STORE = true;
$('#levelScreen').hide();
gwhStore.show();
gwhStoreItems.show();
}
// closes the game store
function closeStore() {
$('#store').hide();
IN_STORE = false;
// go back to level page
gwhStore.hide();
gwhStoreItems.hide();
$('#levelScreen').show();
createEnemies(ENEMY_SIZE);
createBunkers();
if (!PROJECTILES_FALLING) {
cr_prj_id = setInterval(function() {
createProjectile();
}, PROJECTILE_SPAWN_RATE[CUR_LEVEL]);
PROJECTILES_FALLING = true;
}
setTimeout(function() {
$('#levelScreen').hide();
gwhGame.show();
GAME_PAUSED = false;
}, 7000)
}
// continues game with randomly-generated levels
function continueGame() {
GAME_COMPLETE = false;
GAME_OVER = false;
GAME_CONTINUE = true;
$('#winner').hide();
}
// Restarts the game when user presses the r button
function restartGame() {
GAME_OVER = false;
GAME_COMPLETE = false;
GAME_CONTINUE = false;
NUM_ENEMIES = -1;
CUR_LEVEL = 0;
LEVEL_OBJ.level = 1;
SCORE_OBJ.score = 0;
console.log("restarting...");
reset_store();
$('#winner').hide();
gwhOver.hide();
$('.snowball').remove();
$('.projectile').remove();
$('.bunker').remove();
$('#store').hide();
$('#levelScreen').show();
setTimeout(function() {
if (!PROJECTILES_FALLING) {
cr_prj_id = setInterval(function() {
createProjectile();
}, PROJECTILE_SPAWN_RATE[CUR_LEVEL]);
PROJECTILES_FALLING = true;
}
gwhGame.show();
$('#levelScreen').hide();
ENEMY_DIRECTION = "right";
ENEMY_SPEED = LEVEL_SPEED[CUR_LEVEL];
threshold = Math.ceil(ENEMY_DOUBLE_RATIO * ENEMY_PATTERN[CUR_LEVEL][0] * ENEMY_PATTERN[CUR_LEVEL][1]);
NUM_ENEMIES = ENEMY_PATTERN[CUR_LEVEL][1] * ENEMY_PATTERN[CUR_LEVEL][0];
maxEnemyPosX += ENEMY_SIZE;
ENEMY_SIZE = Math.min(100, 100 * 8 / (ENEMY_PATTERN[CUR_LEVEL][0] + 1));
maxEnemyPosX -= ENEMY_SIZE;
createEnemies(ENEMY_SIZE);
createBunkers();
GAME_PAUSED = false;
}, 7000);
}
function reset_store() {
LIVES_OBJ.lives = 1;
SNOWBALL_SIZE = 20;
SNOWBALL_RECHARGE = 400;
NUM_EQUIPPED = 0;
NUM_SNOWBALLS = 1;
SNOWBALL_DURABILITY = 1;
GHOST_SNOWBALL = false;
NUM_EQUIPPED = 0;
SNOWMAN_OBJ.snowmanStyle.pic = "img/defaultSnowman.png";
MORE_LIVES.price = 5000;
OUTFIT1_OBJ.condition = "locked";
OUTFIT1_OBJ.outfitStyle.border = "none";
OUTFIT1_OBJ.pic = "img/snowman2locked.png"
OUTFIT2_OBJ.condition = "locked";
OUTFIT2_OBJ.outfitStyle.border = "none";
OUTFIT2_OBJ.pic = "img/snowman3locked.png";
DOUBLE_SHOT_OBJ.condition = "locked";
DOUBLE_SHOT_OBJ.shotStyle.border = "none";
DOUBLE_SHOT_OBJ.pic = "img/double_shot_locked.png"
TRIPLE_SHOT_OBJ.condition = "locked";
TRIPLE_SHOT_OBJ.shotStyle.border = "none";
TRIPLE_SHOT_OBJ.pic = "img/triple_shot_locked.png"
PIERCING1_OBJ.condition = "locked";
PIERCING1_OBJ.shotStyle.border = "none";
PIERCING1_OBJ.pic = "img/pierce1_locked.png";
PIERCING2_OBJ.condition = "locked";
PIERCING2_OBJ.shotStyle.border = "none";
PIERCING2_OBJ.pic = "img/pierce2_locked.png";
GHOST_OBJ.condition = "locked";
GHOST_OBJ.shotStyle.border = "none";
GHOST_OBJ.pic = "img/ghost_ball_locked.png";
LARGE_OBJ.condition = "locked";
LARGE_OBJ.shotStyle.border = "none";
LARGE_OBJ.pic = "img/large_locked.png";
HUGE_OBJ.condition = "locked";
HUGE_OBJ.shotStyle.border = "none";
HUGE_OBJ.pic = "img/huge_locked.png";
FAST1_OBJ.condition = "locked";
FAST1_OBJ.shotStyle.border = "none";
FAST1_OBJ.pic = "img/fast1_locked.png";
FAST2_OBJ.condition = "locked";
FAST2_OBJ.shotStyle.border = "none";
FAST2_OBJ.pic = "img/fast2_locked.png";
}
/* Things we still need
N - design levels
N - comment everything, remove useless code, replace magic numbers with variables, shrink code using helper functions
*/
| db8e554a9b30a0873e98bbf697b932e8f10861c5 | [
"Markdown",
"JavaScript",
"Text"
] | 3 | Text | benlturner/EECS-493-Final-Project | f1452806d737b1325eee7b986c05d9551135f5f6 | 4028fc6a1f15e9ec0236ec266f9ad3c054ae1684 |
refs/heads/master | <file_sep><h1 align="center">React Native Copilot</h1>
<div align="center">
<p align="center">
<a href="https://github.com/mohebifar/react-native-copilot/actions/workflows/release.yml">
<img src="https://img.shields.io/github/actions/workflow/status/mohebifar/react-native-copilot/release.yml?branch=master&style=flat-square" alt="Build Status" />
</a>
<a href="https://www.npmjs.com/package/react-native-copilot">
<img src="https://img.shields.io/npm/v/react-native-copilot.svg?style=flat-square" alt="NPM Version" />
</a>
<a href="https://www.npmjs.com/package/react-native-copilot">
<img src="https://img.shields.io/npm/dm/react-native-copilot.svg?style=flat-square" alt="NPM Downloads" />
</a>
</p>
</div>
<p align="center">
Step-by-step walkthrough for your react native app!
</p>
<p align="center">
<img src="https://media.giphy.com/media/65VKIzGWZmHiEgEBi7/giphy.gif" alt="React Native Copilot" />
</p>
<p align="center">
<a href="https://expo.io/@mohebifar/copilot-example" >
Demo
</a>
</p>
## Installation
```
yarn add react-native-copilot
# or with npm:
npm install --save react-native-copilot
```
**Optional**: If you want to have the smooth SVG animation, you should install and link [`react-native-svg`](https://github.com/software-mansion/react-native-svg).
## Usage
Wrap the portion of your app that you want to use copilot with inside `<CopilotProvider>`:
```js
import { CopilotProvider } from "react-native-copilot";
const AppWithCopilot = () => {
return (
<CopilotProvider>
<HomeScreen />
</CopilotProvider>
);
};
```
**NOTE**: The old way of using copilot with the `copilot()` HOC maker is deprecated in v3. It will continue to work but it's not recommended and may be removed in the future.
Before defining walkthrough steps for your react elements, you must make them `walkthroughable`. The easiest way to do that for built-in react native components, is using the `walkthroughable` HOC. Then you must wrap the element with `CopilotStep`.
```jsx
import {
CopilotProvider,
CopilotStep,
walkthroughable,
} from "react-native-copilot";
const CopilotText = walkthroughable(Text);
const HomeScreen = () => {
return (
<View>
<CopilotStep text="This is a hello world example!" order={1} name="hello">
<CopilotText>Hello world!</CopilotText>
</CopilotStep>
</View>
);
};
```
Every `CopilotStep` must have these props:
1. **name**: A unique name for the walkthrough step.
2. **order**: A positive number indicating the order of the step in the entire walkthrough.
3. **text**: The text shown as the description for the step.
Additionally, a step may set the **active** prop, a boolean that controls whether the step is used or skipped.
In order to start the tutorial, you can call the `start` function from the `useCopilot` hook:
```js
const HomeScreen = () => {
return (
<View>
<Button title="Start tutorial" onPress={() => start()} />
</View>
);
};
```
If you are looking for a working example, please check out [this link](https://github.com/mohebifar/react-native-copilot/blob/master/example/App.js).
### Overlays and animation
The overlay in react-native-copilot is the component that draws the dark transparent over the screen. React-native-copilot comes with two overlay options: `view` and `svg`.
The `view` overlay uses 4 rectangles drawn around the target element using the `<View />` component. We don't recommend using animation with this overlay since it's sluggish on some devices specially on Android.
The `svg` overlay uses an SVG path component for drawing the overlay. It offers a nice and smooth animation but it depends on `react-native-svg`. If you are using expo, you can install it using:
```
expo install react-native-svg
```
Or if you are using react-native-cli:
```
yarn add react-native-svg
# or with npm
npm install --save react-native-svg
cd ios && pod install
```
You can specify the overlay by passing the `overlay` prop to the `<CopilotProvider />` component:
```js
<CopilotProvider overlay="svg" {/* or "view" */}>
<App />
</CopilotProvider>
```
By default, if overlay is not explicitly specified, the `svg` overlay will be used if `react-native-svg` is installed, otherwise the `view` overlay will be used.
### Custom tooltip and step number UI components
You can customize the tooltip and the step number components by passing a component to the `CopilotProvider` component. If you are looking for an example tooltip component, take a look at [the default ui implementations](https://github.com/mohebifar/react-native-copilot/blob/master/src/components/default-ui).
```js
const TooltipComponent = ({
isFirstStep,
isLastStep,
handleNext,
handleNth,
handlePrev,
handleStop,
currentStep,
}) => (
// ...
);
<CopilotProvider tooltipComponent={TooltipComponent} stepNumberComponent={StepComponent}>
<App />
</CopilotProvider>
```
### Navigating through the tour
The above code snippet shows the functions passed to the tooltip. These are your primary navigation functions. Some notes on navigation:
- `handleNext` and `handlePrev` will move the mask from the current wrapped component immediately to the next.
- You can use `handleStop` in conjunction with `handleNth` to effectively "pause" a tour, allowing for user input, animations or any other interaction that shouldn't have the mask applied. Once you want to pick the tour back up, call `handleNth` on the next tour step.
Note that `handleNth` is 1-indexed, which is in line with what your step orders should look like.
### Custom tooltip styling
You can customize tooltip's wrapper style:
```js
const style = {
backgroundColor: "#9FA8DA",
borderRadius: 10,
paddingTop: 5,
};
<CopilotProvider tooltipStyle={style}>
<App />
</CopilotProvider>;
```
#### Manage tooltip width
By default, the tooltip width is calculated dynamically. You can make it fixed-size by overriding both `width` and `maxWidth`, check the example bellow:
```js
const MARGIN = 8;
const WIDTH = Dimensions.get("window").width - 2 * MARGIN;
<CopioltProvider tooltipStyle={{ width: WIDTH, maxWidth: WIDTH, left: MARGIN }}>
<App />
</CopilotProvider>;
```
### Custom tooltip arrow color
You can customize the tooltip's arrow color:
```js
<CopilotProvider arrowColor="#9FA8DA">
<App />
</CopilotProvider>
```
### Custom overlay color
You can customize the mask color - default is `rgba(0, 0, 0, 0.4)`, by passing a color string to the `CopilotProvider` component.
```js
<CopilotProvider backdropColor="rgba(50, 50, 100, 0.9)">
<App />
</CopilotProvider>
```
### Custom svg mask Path
You can customize the mask svg path by passing a function to the `CopilotProvider` component.
```ts
function SvgMaskPathFn(args: {
size: Animated.valueXY;
position: Animated.valueXY;
canvasSize: {
x: number;
y: number;
};
step: Step;
}): string;
```
Example with circle:
```js
const circleSvgPath = ({ position, canvasSize }) =>
`M0,0H${canvasSize.x}V${canvasSize.y}H0V0ZM${position.x._value},${position.y._value}Za50 50 0 1 0 100 0 50 50 0 1 0-100 0`;
<CopilotProvider svgMaskPath={circleSvgPath}>
<App />
</CopilotProvider>;
```
Example with different overlay for specific step:
Give name prop for the step
```js
<CopilotStep text="This is a hello world example!" order={1} name="hello">
<CopilotText>Hello world!</CopilotText>
</CopilotStep>
```
Now you can return different svg path depending on step name
```js
const customSvgPath = (args) => {
if (args.step?.name === "hello") {
return `M0,0H${canvasSize.x}V${canvasSize.y}H0V0ZM${position.x._value},${position.y._value}Za50 50 0 1 0 100 0 50 50 0 1 0-100 0`;
} else {
return `M0,0H${canvasSize.x}V${canvasSize.y}H0V0ZM${position.x._value},${
position.y._value
}H${position.x._value + size.x._value}V${
position.y._value + size.y._value
}H${position.x._value}V${position.y._value}Z`;
}
};
<CopilotProvider svgMaskPath={customSvgPath}>
<App />
</CopilotProvider>;
```
### Custom components as steps
The components wrapped inside `CopilotStep`, will receive a `copilot` prop with a mutable `ref` and `onLayou` which the outermost rendered element of the component or the element that you want the tooltip be shown around, must extend.
```js
import { CopilotStep } from "react-native-copilot";
const CustomComponent = ({ copilot }) => (
<View {...copilot}>
<Text>Hello world!</Text>
</View>
);
const HomeScreen = () => {
return (
<View>
<CopilotStep text="This is a hello world example!" order={1} name="hello">
<CustomComponent />
</CopilotStep>
</View>
);
};
```
### Custom labels (for i18n)
You can localize labels:
```js
<CopilotProvider
labels={{
previous: "Vorheriger",
next: "Nächster",
skip: "Überspringen",
finish: "Beenden"
}}
>
```
### Adjust vertical position
In order to adjust vertical position pass `verticalOffset` to the `CopilotProvider` component.
```js
<CopilotProvider verticalOffset={36}>
```
### Triggering the tutorial
Use `const {start} = useCopilot()` to trigger the tutorial. You can either invoke it with a touch event or in `useEffect` to start after the comopnent mounts. Note that the component and all its descendants must be mounted before starting the tutorial since the `CopilotStep`s need to be registered first.
### Usage inside a ScrollView
Pass the ScrollView reference as the second argument to the `start()` function.
eg `start(undefined, scrollViewRef)`
```js
import { ScrollView } from "react-native";
class HomeScreen {
componentDidMount() {
// Starting the tutorial and passing the scrollview reference.
this.props.start(false, this.scrollView);
}
componentWillUnmount() {
// Don't forget to disable event handlers to prevent errors
this.props.copilotEvents.off("stop");
}
render() {
<ScrollView ref={(ref) => (this.scrollView = ref)}>// ...</ScrollView>;
}
}
```
### Listening to the events
`useCopilot` provides a `copilotEvents` function prop to allow you to track the progress of the tutorial. It utilizes [mitt](https://github.com/developit/mitt) under the hood.
List of available events is:
- `start` — Copilot tutorial has started.
- `stop` — Copilot tutorial has ended or skipped.
- `stepChange` — Next step is triggered. Passes [`Step`](https://github.com/mohebifar/react-native-copilot/blob/master/src/types.js#L2) instance as event handler argument.
**Example:**
```js
import { useCopilot } from "react-native-copilot";
const HomeScreen = () => {
const { copilotEvents } = useCopilot();
useEffect(() => {
const listener = () => {
// Copilot tutorial finished!
};
copilotEvents.on("stop", listener);
return () => {
copilotEvents.off("stop", listener)
};
}, []);
return (
// ...
);
}
```
## Contributing
Issues and Pull Requests are always welcome.
If you are interested in becoming a maintainer, get in touch with us by sending an email or opening an issue. You should already have code merged into the project. Active contributors are encouraged to get in touch.
Creation of this project was sponsored by OK GROW!
<file_sep>Issues and Pull Requests are always welcome.
Please read OK Grow's global [contribution guidelines](https://github.com/okgrow/guides/blob/master/docs/OpenSource-Contributing.md).
If you are interested in becoming a maintainer, get in touch with us by sending an email or opening an issue. You should already have code merged into the project. Active contributors are encouraged to get in touch.
Please note that all interactions in @okgrow's repos should follow our [Code of Conduct](https://github.com/okgrow/guides/blob/master/docs/OpenSource-CodeOfConduct.md).
<file_sep>import type {
Animated,
LayoutRectangle,
NativeMethods,
ViewStyle,
} from "react-native";
export type WalktroughedComponent = NativeMethods & React.ComponentType<any>;
export interface Step {
name: string;
order: number;
visible: boolean;
wrapperRef: React.RefObject<NativeMethods>;
measure: () => Promise<LayoutRectangle>;
text: string;
}
export interface CopilotContext {
registerStep: (step: Step) => void;
unregisterStep: (name: string) => void;
getCurrentStep: () => Step | undefined;
}
export interface ValueXY {
x: number;
y: number;
}
export type SvgMaskPathFunction = (args: {
size: Animated.ValueXY;
position: Animated.ValueXY;
canvasSize: ValueXY;
step: Step;
}) => string;
export type StepsMap = Record<string, Step>;
export type EasingFunction = (value: number) => number;
export type Labels = Partial<
Record<"skip" | "previous" | "next" | "finish", string>
>;
export interface TooltipProps {
labels: Labels;
}
export interface MaskProps {
size: ValueXY;
position: ValueXY;
style: ViewStyle;
easing?: EasingFunction;
animationDuration: number;
animated: boolean;
backdropColor: string;
svgMaskPath?: SvgMaskPathFunction;
layout: {
width: number;
height: number;
};
onClick?: () => any;
currentStep: Step;
}
export interface CopilotOptions {
easing?: ((value: number) => number) | undefined;
overlay?: "svg" | "view";
animationDuration?: number;
tooltipComponent?: React.ComponentType<TooltipProps>;
tooltipStyle?: ViewStyle;
stepNumberComponent?: React.ComponentType<any >;
animated?: boolean;
labels?: Labels;
androidStatusBarVisible?: boolean;
svgMaskPath?: SvgMaskPathFunction;
verticalOffset?: number;
arrowColor?: string;
arrowSize?: number
margin?: number
stopOnOutsideClick?: boolean;
backdropColor?: string;
}
<file_sep>/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
presets: ["module:metro-react-native-babel-preset"],
};
<file_sep># Change Log
## 3.2.1
### Patch Changes
- 3a6dd5a: Fix malformed field crash and add more config (arrowSize and margin)
## 3.2.0
### Minor Changes
- 0d8362a: Remove Tooltip and StepNumber passed props in favor of useCopilot context
Un-register the step after name change and re-register with the new name
Add tests for CopilotStep
## 3.1.0
### Minor Changes
- 312fba4: Expose more functions through the public API
Expose `stop`, `goToNext`, `goToNth`, and `goToPrev` through the `useCopilot` hook
Export `DefaultUI` from the module's entry to access the default Tooltip and StepNumber components
## 3.0.1
### Patch Changes
- 3a0f6e0: Migrate to TS and add CopilotProvider
## 3.0.0
### Major Changes
- f2b45c7: Migrate to TS and deprecate HOC
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [1.0.0] - 2017-06-05
<file_sep>import { Ionicons } from "@expo/vector-icons";
import React, { useEffect, useState } from "react";
import {
Image,
SafeAreaView,
StyleSheet,
Switch,
Text,
TouchableOpacity,
View,
} from "react-native";
import {
CopilotProvider,
CopilotStep,
walkthroughable,
useCopilot,
} from "react-native-copilot";
const WalkthroughableText = walkthroughable(Text);
const WalkthroughableImage = walkthroughable(Image);
function App() {
const { start, copilotEvents } = useCopilot();
const [secondStepActive, setSecondStepActive] = useState(true);
const [lastEvent, setLastEvent] = useState(null);
useEffect(() => {
copilotEvents.on("stepChange", (step) => {
setLastEvent(`stepChange: ${step.name}`);
});
copilotEvents.on("start", () => {
setLastEvent(`start`);
});
copilotEvents.on("stop", () => {
setLastEvent(`stop`);
});
}, [copilotEvents]);
return (
<SafeAreaView style={styles.container}>
<CopilotStep
text="Hey! This is the first step of the tour!"
order={1}
name="openApp"
>
<WalkthroughableText style={styles.title}>
{'Welcome to the demo of\n"React Native Copilot"'}
</WalkthroughableText>
</CopilotStep>
<View style={styles.middleView}>
<CopilotStep
active={secondStepActive}
text="Here goes your profile picture!"
order={2}
name="secondText"
>
<WalkthroughableImage
source={{
uri: "https://pbs.twimg.com/profile_images/527584017189982208/l3wwN-l-_400x400.jpeg",
}}
style={styles.profilePhoto}
/>
</CopilotStep>
<View style={styles.activeSwitchContainer}>
<Text>Profile photo step activated?</Text>
<View style={{ flexGrow: 1 }} />
<Switch
onValueChange={(secondStepActive) =>
setSecondStepActive(secondStepActive)
}
value={secondStepActive}
/>
</View>
<TouchableOpacity style={styles.button} onPress={() => start()}>
<Text style={styles.buttonText}>START THE TUTORIAL!</Text>
</TouchableOpacity>
<View style={styles.eventContainer}>
<Text>{lastEvent && `Last event: ${lastEvent}`}</Text>
</View>
</View>
<View style={styles.row}>
<CopilotStep
text="Here is an item in the corner of the screen."
order={3}
name="thirdText"
>
<WalkthroughableText style={styles.tabItem}>
<Ionicons name="apps" size={25} color="#888" />
</WalkthroughableText>
</CopilotStep>
<Ionicons
style={styles.tabItem}
name="airplane"
size={25}
color="#888"
/>
<Ionicons
style={styles.tabItem}
name="ios-globe"
size={25}
color="#888"
/>
<Ionicons
style={styles.tabItem}
name="ios-navigate-outline"
size={25}
color="#888"
/>
<Ionicons
style={styles.tabItem}
name="ios-rainy"
size={25}
color="#888"
/>
</View>
</SafeAreaView>
);
}
const AppwithProvider = () => (
<CopilotProvider stopOnOutsideClick androidStatusBarVisible>
<App />
</CopilotProvider>
);
export default AppwithProvider;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
paddingTop: 25,
},
title: {
fontSize: 24,
textAlign: "center",
},
profilePhoto: {
width: 140,
height: 140,
borderRadius: 70,
marginVertical: 20,
},
middleView: {
flex: 1,
alignItems: "center",
},
button: {
backgroundColor: "#2980b9",
paddingVertical: 10,
paddingHorizontal: 15,
},
buttonText: {
color: "white",
fontSize: 16,
},
row: {
flexDirection: "row",
justifyContent: "space-between",
},
tabItem: {
flex: 1,
textAlign: "center",
},
activeSwitchContainer: {
flexDirection: "row",
justifyContent: "space-between",
marginBottom: 20,
alignItems: "center",
paddingHorizontal: 25,
},
eventContainer: {
marginTop: 20,
},
});
<file_sep>import { useCallback, useMemo, useReducer, useState } from "react";
import { type Step, type StepsMap } from "../types";
type Action =
| {
type: "register";
step: Step;
}
| {
type: "unregister";
stepName: string;
};
export const useStepsMap = () => {
const [currentStep, setCurrentStepState] = useState<Step | undefined>(
undefined
);
const [steps, dispatch] = useReducer((state: StepsMap, action: Action) => {
switch (action.type) {
case "register":
return {
...state,
[action.step.name]: action.step,
};
case "unregister": {
const { [action.stepName]: _, ...rest } = state;
return rest;
}
default:
return state;
}
}, {});
const orderedSteps = useMemo(
() => Object.values(steps).sort((a, b) => a.order - b.order),
[steps]
);
const stepIndex = useCallback(
(step = currentStep) =>
step
? orderedSteps.findIndex(
(stepCandidate) => stepCandidate.order === step.order
)
: -1,
[currentStep, orderedSteps]
);
const currentStepNumber = useMemo(
(step = currentStep) => stepIndex(step) + 1,
[currentStep, stepIndex]
);
const getFirstStep = useCallback(() => orderedSteps[0], [orderedSteps]);
const getLastStep = useCallback(
() => orderedSteps[orderedSteps.length - 1],
[orderedSteps]
);
const getPrevStep = useCallback(
(step = currentStep) => step && orderedSteps[stepIndex(step) - 1],
[currentStep, stepIndex, orderedSteps]
);
const getNextStep = useCallback(
(step = currentStep) => step && orderedSteps[stepIndex(step) + 1],
[currentStep, stepIndex, orderedSteps]
);
const getNthStep = useCallback(
(n: number) => orderedSteps[n - 1],
[orderedSteps]
);
const isFirstStep = useMemo(
() => currentStep === getFirstStep(),
[currentStep, getFirstStep]
);
const isLastStep = useMemo(
() => currentStep === getLastStep(),
[currentStep, getLastStep]
);
const registerStep = useCallback((step: Step) => {
dispatch({ type: "register", step });
}, []);
const unregisterStep = useCallback((stepName: string) => {
dispatch({ type: "unregister", stepName });
}, []);
return {
currentStepNumber,
getFirstStep,
getLastStep,
getPrevStep,
getNextStep,
getNthStep,
isFirstStep,
isLastStep,
currentStep,
setCurrentStepState,
steps,
registerStep,
unregisterStep,
};
};
<file_sep>import { defineConfig } from "tsup";
import fs from "fs/promises";
import path from "path";
export default defineConfig({
entry: ["src/index.ts"],
format: "cjs",
sourcemap: true,
dts: true,
external: ["react", "react-native", "react-native-svg"],
platform: "neutral",
async onSuccess() {
if (process.env.NODE_ENV === "development") {
const exampleOutputPath = path.resolve(
"./example/node_modules/react-native-copilot"
);
const exampleOutputNodeModulesPath = path.resolve(
exampleOutputPath,
"node_modules"
);
await Promise.all(
["dist/index.js", "dist/index.d.ts"].map(async (file) => {
const outputPath = path.resolve(exampleOutputPath, file);
console.log("Copying file: ", file, "to ->", outputPath);
await fs.copyFile(file, outputPath);
})
);
await fs.rm(exampleOutputNodeModulesPath, {
recursive: true,
force: true,
});
console.log("Copied files to example project");
}
},
});
<file_sep>import { StepNumber } from "./components/default-ui/StepNumber";
import { Tooltip } from "./components/default-ui/Tooltip";
export { walkthroughable } from "./hocs/walkthroughable";
export { CopilotStep } from "./components/CopilotStep";
export { CopilotProvider, useCopilot } from "./contexts/CopilotProvider";
export type { CopilotOptions as CopilotProps, TooltipProps } from "./types";
export const DefaultUI = {
StepNumber,
Tooltip,
};
<file_sep>import { useEffect, useRef, useState } from "react";
/**
* A hook like useState that allows you to use await the setter
*/
export const useStateWithAwait = <T = any>(
initialState: T
): [T, (newValue: T) => Promise<void>] => {
const endPending = useRef(() => {});
const newDesiredValue = useRef(initialState);
const [state, setState] = useState(initialState);
const setStateWithAwait = async (newState: T) => {
const pending = new Promise<void>((resolve) => {
endPending.current = resolve;
});
newDesiredValue.current = newState;
setState(newState);
await pending;
};
useEffect(() => {
if (state === newDesiredValue.current) {
endPending.current();
}
}, [state]);
return [state, setStateWithAwait];
};
<file_sep>import { StyleSheet } from "react-native";
export const STEP_NUMBER_RADIUS: number = 14;
export const STEP_NUMBER_DIAMETER: number = STEP_NUMBER_RADIUS * 2;
export const ZINDEX: number = 100;
export const MARGIN: number = 13;
export const OFFSET_WIDTH: number = 4;
export const ARROW_SIZE: number = 6;
export const styles = StyleSheet.create({
container: {
position: "absolute",
left: 0,
top: 0,
right: 0,
bottom: 0,
zIndex: ZINDEX,
},
arrow: {
position: "absolute",
borderColor: "transparent",
borderWidth: ARROW_SIZE,
},
tooltip: {
position: "absolute",
paddingTop: 15,
paddingHorizontal: 15,
backgroundColor: "#fff",
borderRadius: 3,
overflow: "hidden",
},
tooltipText: {},
tooltipContainer: {
flex: 1,
},
stepNumberContainer: {
position: "absolute",
width: STEP_NUMBER_DIAMETER,
height: STEP_NUMBER_DIAMETER,
overflow: "hidden",
zIndex: ZINDEX + 1,
},
stepNumber: {
flex: 1,
alignItems: "center",
justifyContent: "center",
borderWidth: 2,
borderRadius: STEP_NUMBER_RADIUS,
borderColor: "#FFFFFF",
backgroundColor: "#27ae60",
},
stepNumberText: {
fontSize: 10,
backgroundColor: "transparent",
color: "#FFFFFF",
},
button: {
padding: 10,
},
buttonText: {
color: "#27ae60",
},
bottomBar: {
marginTop: 10,
flexDirection: "row",
justifyContent: "flex-end",
},
overlayRectangle: {
position: "absolute",
backgroundColor: "rgba(0,0,0,0.2)",
left: 0,
top: 0,
bottom: 0,
right: 0,
},
overlayContainer: {
position: "absolute",
left: 0,
top: 0,
bottom: 0,
right: 0,
},
});
| 9aac429fdd00345f177f421735826b139de157cd | [
"Markdown",
"TypeScript",
"JavaScript"
] | 11 | Markdown | mohebifar/react-native-copilot | 854cfe31156c86ee7ea35bae3086fe55ef5206e5 | e099de97e10f181e0e35bf654c5fb3d74523579c |
refs/heads/main | <file_sep><?php
session_start();
function ranking_ricchezza($username)
{
include 'db_info.php';
$query = "SELECT username
FROM utente
ORDER BY monete DESC";
$result = $con->query($query);
$conta = 1;
while($row = $result->fetch_array())
{
if($row['username'] == $username)
{
return $conta; // restituisco il rank associato all'utente
}
$conta++;
}
}
function percentuale_ricchezza($username)
{
include 'db_info.php';
$query = "SELECT monete FROM utente WHERE username = '{$username}'";
$money = $con->query($query);
while($row = $money->fetch_array())
{
$money = $row['monete'];
break;
}
$query = "SELECT sum(monete) as tot
FROM utente";
$result = $con->query($query);
while($row = $result->fetch_array())
{
return round(100*($money/$row['tot']));
}
}
function tempo_gioco($username)
{
include 'db_info.php';
$query = "SELECT tempoGioco
FROM utente
WHERE username = '{$username}'";
$result = $con->query($query);
while($row = $result->fetch_array())
{
return $row['tempoGioco'];
}
}
function ranking_tempo($username)
{
include 'db_info.php';
$query = "SELECT username
FROM utente
ORDER BY tempoGioco DESC";
$result = $con->query($query);
$conta = 1;
while($row = $result->fetch_array())
{
if($row['username'] == $username)
{
return $conta; // restituisco il rank associato all'utente
}
$conta++;
}
}
$stats = array();
$stats['rank_ricchezza'] = ranking_ricchezza($_SESSION['name']);
$stats['ricchezza_globale'] = percentuale_ricchezza($_SESSION['name']);
$stats['tempo_tot'] = tempo_gioco($_SESSION['name']);
$stats['rank_tempo'] = ranking_tempo($_SESSION['name']);
print json_encode($stats);
?>
<file_sep><?php
include 'db_info.php';
session_start();
$quote = array();
$totpunti = 0;
$pattern = "/[,]/";
$corridori = preg_split($pattern, $_POST['ordine']);
$query = "SELECT sum(punteggio) as somma FROM corridore";
$result = $con->query($query);
while($row = $result->fetch_array())
{
$totpunti = $row['somma'];
}
$rank = 0;
for ($i=0; $i < 6; $i++) {
++$rank;
$query = "SELECT punteggio FROM corridore WHERE nome = '{$corridori[$i]}' order by punteggio";
$result = $con->query($query);
while($row = $result->fetch_array())
{
$punteggio = $row['punteggio'];
}
$quote[$i] = ($totpunti/($punteggio*2)) + ( ($rank <= 3)? rand(-1, 0) : rand(2, 5) );
}
print json_encode($quote);
?>
<file_sep><?php
session_start();
include 'db_info.php';
$primo = $_POST['primoPosto'];
$secondo = $_POST['secondoPosto'];
$terzo = $_POST['terzoPosto'];
// primo posto 3 punti, secondo 2, terzo 1
$query = "UPDATE corridore
SET vittorie = vittorie + 1, punteggio = punteggio + 3
WHERE nome = '{$primo}'";
if ($result = $con->query($query)) {
echo $primo." primo";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
$query = "UPDATE corridore
SET 2posto = 2posto + 1, punteggio = punteggio + 2
WHERE nome = '{$secondo}'";
if ($result = $con->query($query)) {
echo $primo." primo";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
$query = "UPDATE corridore
SET 3posto = 3posto + 1, punteggio = punteggio + 1
WHERE nome = '{$terzo}'";
if ($result = $con->query($query)) {
echo $primo." primo";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>
<file_sep><?php // non funge
include 'db_info.php';
if (isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$ripeti_password = $_POST['<PASSWORD>ti-password'];
$email_ck = $_POST['email'];
if($email_ck === '')
$email_ck = NULL;
// controllo caratteri username
$isUsernameValid = filter_var(
$username,
FILTER_VALIDATE_REGEXP, [
"options" => [
"regexp" => "/^[a-z\d_]{3,20}$/i"
]
]
);
$pwdLenght = mb_strlen($password);
// serie di errori
if (empty($username) || empty($password)) {
$msg = 'Compila tutti i campi %s';
} elseif (false === $isUsernameValid) {
$msg = 'Lo username non è valido. Sono ammessi solamente caratteri
alfanumerici e l\'underscore. Lunghezza minina 3 caratteri.
Lunghezza massima 20 caratteri';
}/* elseif ($pwdLenght < 8 || $pwdLenght > 20) {
$msg = 'Lunghezza minima password 8 caratteri.
Lunghezza massima 20 caratteri';
}*/ elseif ($password != $ripeti_password) {
$msg = 'Forse non sei così sicuro della tua password...
Le due password devono essere uguali!!';
}
else { // se tutto ok
$password_hash = password_hash($password, PASSWORD_BCRYPT); // cripto la pw
// controllo se username esiste già
if ($stmt = $con->prepare('SELECT username FROM utente WHERE username = ?'))
{
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0)
{
$msg = 'Username già in uso %s';
}
else // inserisco i dati
{
$sql = 'INSERT INTO utente (username, password, email, monete)
VALUES ("'.$username.'", "'.$password_hash.'", "'.$email_ck.'", 10);';
$result = $con->query($sql);
if ($result) {
header('Location: ../html/accedi.html');
} else {
$msg = "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
}
printf($msg, '<a href="../html/iscriviti.html">torna indietro</a>');
}
?>
<file_sep><?php
session_start();
include 'db_info.php';
$username = $_SESSION['name'];
$testo = $_POST['feedback_text'];
$query = "INSERT INTO feedback
VALUES ('{$username}', '{$testo}')";
$con->query($query);
header('Location: gioco.php');
?>
<file_sep>
function Corridore(y, speedArr, img) {
if(gioco.logged)
this.name = img.slice(7, -4);
else
this.name = img.slice(6, -4);
this.x = 0;
this.y = y;
this.speed = speedArr[0];
this.speedArr = new Array();
this.speedArr = speedArr;
this.arrived = false;
this.canvas = document.getElementById('canvas');
this.ctx = canvas.getContext("2d");
//sprite e spritesheet
this.sprite = new Image();
this.sprite.src = img;
//dimensioni effettive di un singolo sprite nello spritesheet
this.spriteWidth = 112/7;
this.spriteHeight = 96/4 + 1;
//dimensioni che vogliamo dare al corridore durante la corsa
this.width = this.spriteWidth*1.5;
this.height = this.spriteHeight*1.5;
this.inizia_a_tagliare_x = this.currFrame * this.spriteWidth;
this.inizia_a_tagliare_y = 2 * this.spriteHeight;
// variabile per le colonne
this.currFrame = 0; // frame corrente
this.corre_frame = 4; // numero di frame che ha lo spritesheet per la corsa
this.updateFrame = function(){
this.currFrame = ++this.currFrame % this.corre_frame;
this.inizia_a_tagliare_x = this.currFrame * this.spriteWidth;
this.x += this.speed;
if(this.x+this.width >= canvas.width)
{
this.x = canvas.width - this.width;
this.arrived = true;
}
}
this.updateSpeed = function(){
for (var i = 0; i < 40; i++) {
if(this.x >= 25*i && this.x < 25*(i+1))
this.speed = this.speedArr[i];
}
}
this.update = function(){
if(this.arrived == false)
{
this.ctx.clearRect(this.x, this.y, this.width, this.height);
this.updateFrame();
this.updateSpeed();
this.ctx.drawImage(this.sprite, this.inizia_a_tagliare_x, this.inizia_a_tagliare_y, this.spriteWidth, this.spriteHeight, this.x, this.y, this.width, this.height);
}
else
{
this.ctx.clearRect(this.x, this.y, this.width, this.height);
this.ctx.drawImage(this.sprite, 0, 0, this.spriteWidth, this.spriteHeight, this.x, this.y, this.width, this.height);
}
}
}
<file_sep>function Gara() // funzione che gestisce la gara
{
gioco.START_premuto = true;
clearInterval(gioco.intro);
for (var i = 0; i < gioco.corridori.length; i++) {
if(gioco.corridori[i].arrived == true)
{
if(gioco.posizionamenti[i] == 0){
++gioco.posizione;
gioco.posizionamenti[i] = gioco.posizione;
// context .fillText ( text, x, y, maxWidth );
if(gioco.posizione <= 3)
{
switch (gioco.posizione) {
case 1:
gioco.primo = gioco.corridori[i].name;
break;
case 2:
gioco.secondo = gioco.corridori[i].name;
break;
case 3:
gioco.terzo = gioco.corridori[i].name;
break;
}
gioco.ctx.font = "20px Georgia";
gioco.ctx.fillText(gioco.posizione, gioco.corridori[i].x - 30, gioco.corridori[i].y + 25);
gioco.ctx.fillText(gioco.corridori[i].name, gioco.corridori[i].x - 200, gioco.corridori[i].y + 25);
}
}
}
else
if(gioco.garaFinita==false)
gioco.corridori[i].update();
}
var arrivati = 0;
for (var i = 0; i < gioco.corridori.length; i++)
{
if(gioco.corridori[i].arrived == true)
++arrivati;
}
if(arrivati == 6)
{
if(gioco.garaFinita==false)
{
risquoti();
if(gioco.logged == true)
esito_corsa(gioco.primo, gioco.secondo, gioco.terzo);
}
gioco.garaFinita = true;
return;
}
}
<file_sep>
function Gioco()
{
this.canvas = document.getElementById('canvas');
this.ctx = canvas.getContext("2d");
this.tempo_gioco = 0; // in minuti
this.logged = false;
this.corridori = new Array();
for (var i = 0; i < this.corridori.length; i++) {
this.corridori[i] = new Corridore();
}
this.immagini = [ "./img/<NAME>.png",
"./img/Jonny.png",
"./img/<NAME>.png",
"./img/Villan Default.png",
"./img/<NAME>.png",
"./img/Avatar Punk.png" ];
this.nomi = [ "<NAME>",
"Jonny",
"<NAME>",
"<NAME>",
"<NAME>",
"Avatar Punk" ];
// gara gara.js
this.posizione = 0;
this.posizionamenti = [0,0,0,0,0,0];
this.primo;
this.secondo;
this.terzo;
// controllo
this.partiti = false;
this.garaFinita = true;
this.START_premuto = false;
this.DONEpremuto = false;
this.intro;
this.load = true; //non sfa il salvataggio dati all'avvio
// economia
this.monete;
document.getElementById("monete").innerText = 1;
document.getElementById("monetePopup").innerText = 1;
this.quoteW = new Array();
this.scommesseW = [0,0,0,0,0,0];
this.quoteA = new Array();
this.scommesseA = [0,0,0,0];
this.vincita = 0;
}
var gioco = new Gioco();
<file_sep><?php
include 'db_info.php';
session_start();
$info = array();
$info['username'] = $_SESSION['name'];
$username = $info['username'];
$query = "SELECT monete FROM utente WHERE username = '{$username}'";
$result = $con->query($query);
while($row = $result->fetch_array())
{
$info['monete'] = $row['monete'];
}
// '{}'
print json_encode($info);
?>
<file_sep>
function avvio() // onload
{
if(gioco.logged == true)
{
get_user_info();
aggiorna_stats();
classifica_utenti();
}
else {
gioco.monete = 1;
document.getElementById("monete").innerText = Math.round(gioco.monete*100)/100;
document.getElementById("monetePopup").innerText = Math.round(gioco.monete*100)/100;
}
classifica_corridori();
refresh();
setInterval(updateMonete, 6000); //60000 incrementa le monete
setInterval(function(){gioco.tempo_gioco++}, 60000); // un minuto
if(gioco.logged == true)
setInterval(aggiorna_stats, 60000);
}
// funzioni chiamate dall'utente
function refresh() // onclick AGAIN
{
if(gioco.logged == true && gioco.load == false)
{
gioco.logged++;
SalvataggioDati();
}
gioco.load = false;
gioco.START_premuto = false;
gioco.DONEpremuto = false;
gioco.garaFinita = true;
gioco.ctx.clearRect(0,0,canvas.width, canvas.height);
clearInterval(gioco.partiti);
// azzera corsa
gioco.posizione = 0;
gioco.posizionamenti = [0, 0, 0, 0, 0, 0];
gioco.primo = "";
gioco.secondo = "";
gioco.terzo = "";
shuffle(gioco.immagini);
for (var i = 0; i < gioco.immagini.length; i++) {
var arr = speedArrGenerator();
gioco.corridori[i] = new Corridore(83*i + 20, arr, gioco.immagini[i]);
}
if(gioco.logged == true)
{
azzera_scommesse_logged();
}
else
azzera_scommesse();
};
function IniziaGara() // onclick START
{
if(gioco.START_premuto == false)
{
gioco.ctx.clearRect(0,0,canvas.width, canvas.height);
gioco.garaFinita = false;
gioco.partiti = setInterval(Gara, 100);
}
}
// gestione popup scommesse
function apri_popup_scommesse() // BET --> onclick
{
if(gioco.garaFinita == true && gioco.DONEpremuto == false)
{
document.getElementById("popup-scommesse").classList.add("active");
document.getElementById("overlay").classList.add("active");
}
}
function chiudi_popup_scommesse() // close-button --> onclick
{
document.getElementById("popup-scommesse").classList.remove("active");
document.getElementById("overlay").classList.remove("active");
}
<file_sep>
<?php
session_start();
include 'db_info.php';
$nomeUtente = $_SESSION['name'];
$monete_saved = $_POST['monete_saved'];
$tempo_gioco_saved = $_POST['tempo_gioco_saved'];
$query = "UPDATE utente
SET monete ='{$monete_saved}', tempoGioco = ('{$tempo_gioco_saved}' + tempoGioco)
WHERE username = '{$nomeUtente}'";
if ($result = $con->query($query)) {
echo $tempo_gioco_saved." ".$monete_saved ;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>
<file_sep>// Fisher–Yates shuffle based
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function randGenerator(min, max)
{
return Math.floor(Math.random() * (max-min))+ min;
}
function speedArrGenerator()
{
var sArr = new Array(); //risultato
for (var i = 0; i < 40; i++) {
if(Math.floor(Math.random() * 10) == 0)
sArr[i] = 13;
else
sArr[i] = randGenerator(5, 10);
}
return sArr;
}
<file_sep><?php
session_start();
include 'db_info.php';
// se l'utente non è loggato torna alla pagina accedi
if (!isset($_SESSION['loggedin'])) { // variabile definita in autenticate.php
header('Location: accedi.html');
exit;
}
?>
<!DOCTYPE html>
<html lang="it" dir="ltr">
<head>
<meta charset="utf-8">
<title>BetSpritesRace</title>
<link rel="icon" href="../img/logo.ico" />
<link rel="stylesheet" href="../css/index.css">
<link rel="stylesheet" href="../css/popup.css">
<link rel="stylesheet" href="../css/gioco.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="avvio()">
<h1>BetSpritesRace</h1>
<header>
<ul>
<li><a href="#MioProfilo">Mio Profilo</a></li>
<li><a href="#Corridori">Corridori</a></li>
<li><a href="#Classifica">Classifica</a></li>
</ul>
<?php echo '<p id="benvenuto">Benvenuto '.$_SESSION['name'].'!!</p>' ?>
<a id="accedi" href="logout.php">LOGOUT</a>
</header>
<canvas id="canvas" width="1000" height="500"></canvas>
<div class="comandi">
<button type="button" id="START" onclick="IniziaGara()">START</button> <br>
<button type="button" id="BET" onclick="apri_popup_scommesse()">BET</button>
<p id="monete">0000</p>
<button type="button" id="AGAIN" onclick="refresh()">AGAIN</button>
<button type="button" id="SAVE" onclick="SalvataggioDati()">SAVE</button>
</div>
<div id="popup-scommesse">
<button id="close-button" onclick="chiudi_popup_scommesse()">×</button>
<table>
<tr>
<th colspan="2">Vincitori</th>
<th colspan="2">Accoppiate</th>
</tr>
<tr>
<td id="quota1"></td>
<td> <input type="number" min="1" max="999" id="bet1"> </td>
</tr>
<tr>
<td id="quota2"></td>
<td> <input type="number" min="1" max="999" id="bet2"> </td>
</tr>
<tr>
<td id="quota3"></td>
<td> <input type="number" min="1" max="999" id="bet3"> </td>
<td id="quota3_a"></td>
<td> <input type="number" min="1" max="999" id="bet3_a"> </td>
</tr>
<tr>
<td id="quota4"></td>
<td> <input type="number" min="1" max="999" id="bet4"> </td>
<td id="quota4_a"></td>
<td> <input type="number" min="1" max="999" id="bet4_a"> </td>
</tr>
<tr>
<td id="quota5"></td>
<td> <input type="number" min="1" max="999" id="bet5"> </td>
<td id="quota5_a"></td>
<td> <input type="number" min="1" max="999" id="bet5_a"> </td>
</tr>
<tr>
<td id="quota6"></td>
<td> <input type="number" min="1" max="999" id="bet6"> </td>
<td id="quota6_a"></td>
<td> <input type="number" min="1" max="999" id="bet6_a"> </td>
</tr>
</table>
<button type="button" id="okBet" onclick="salvaScommesse()">DONE!</button>
<p id="md">Monete disponibili:</p> <p id="monetePopup"></p>
</div>
<div id="overlay"></div>
<div class="info">
<article id="MioProfilo">
<h2>Il tuo profilo</h2>
<div id="rank_ricchezza"></div>
<div id="ricchezza_globale"></div>
<div id="tempoGioco"></div>
<div id="rank_tempo"></div>
</article>
<article id="Corridori">
</article>
<article id="Classifica">
</article>
</div>
<script src="../js/funzioni_utilita.js"></script>
<script src="../js/corridore.js"></script>
<script src="../js/gioco.js"></script>
<script src="../js/get_info.js"></script>
<script src="../js/get_quote.js"></script>
<script src="../js/economia_loggato.js"></script>
<script src="../js/economia.js"></script>
<script src="../js/gara.js"></script>
<script src="../js/ajax.js"></script>
<script src="../js/main.js"></script>
</body>
</html>
<file_sep># BetspritesRace
sito web che simula una gara tra sprites dove l'utente può scommettere sul vincitore
<file_sep><?php
include 'db_info.php';
session_start();
$classifica = array();
$query = "SELECT nome, punteggio FROM corridore ORDER BY punteggio DESC";
$result = $con->query($query);
$i = 0;
while($row = $result->fetch_array())
{
$utente = array();
$classifica[$i] = $row['nome'];
$i++;
$classifica[$i] = round($row['punteggio']);
$i++;
}
// '{}'
print json_encode($classifica);
?>
<file_sep>
function azzera_scommesse()
{
gioco.scommesseW = [0, 0, 0, 0, 0, 0];
gioco.scommesseA = [0, 0, 0, 0];
gioco.vincita = 0;
for (var i = 0; i < 6; i++) {
document.getElementById("bet"+(i+1)).value = "";
if(i > 1)
document.getElementById("bet"+(i+1) + "_a").value = "";
// assegno le quote casuali
gioco.quoteW[i] = Math.round((Math.random()*3 + 1)*100)/100;
document.getElementById("quota" + (i+1)).innerText = gioco.corridori[i].name + ": " + gioco.quoteW[i];
if(i > 1)
{
gioco.quoteA[i] = Math.round((Math.random()*13 + 1)*100)/100;
document.getElementById("quota" + (i+1) + "_a").innerText = gioco.corridori[i].name + "-" + gioco.corridori[i-2].name + ": " + gioco.quoteA[i];
}
}
};
function risquoti()
{
for (var i = 0; i < gioco.posizionamenti.length; i++) {
if(gioco.posizionamenti[i] == 1 & gioco.scommesseW[i] > 0)
{
gioco.vincita = gioco.scommesseW[i]*gioco.quoteW[i];
gioco.monete += gioco.vincita;
if(gioco.vincita > 0)
{
window.alert("hai vinto\n" + gioco.vincita + " monete!!");
console.log("hai vinto\n" + gioco.vincita + " monete!!");
}
gioco.vincita = 0;
if(i > 1)
{
if(gioco.posizionamenti[i-2] == 2)
{
gioco.vincita = gioco.scommesseA[i-2]*gioco.quoteA[i];
gioco.monete += gioco.vincita;
console.log( gioco.scommesseA[i-2] + '*' + gioco.quoteA[i]);
}
}
if(gioco.vincita > 0)
{
window.alert("hai vinto\n" + gioco.vincita + " monete!!");
console.log("hai vinto\n" + gioco.vincita + " monete!!");
}
document.getElementById("monete").innerText = Math.round(gioco.monete*100)/100;
document.getElementById("monetePopup").innerText = Math.round(gioco.monete*100)/100;
}
}
}
function updateMonete()
{
++gioco.monete;
if(gioco.monete < 10)
++gioco.monete;
document.getElementById("monete").innerText = Math.round(gioco.monete*100)/100;
document.getElementById("monetePopup").innerText = Math.round(gioco.monete*100)/100;
// metto il valore delle monete come tetto massimo di scommessa
for (var i = 0; i < 6; i++) {
document.getElementById("bet" + (i+1)).max = gioco.monete;
if(i > 1)
document.getElementById("bet" + (i+1) + "_a").max = gioco.monete;
}
};
function salvaScommesse() // okBet --> onclick
{
gioco.DONEpremuto = true;
var totScommesse = 0;
var sA = 0;
for (var i = 0; i < 6; i++) {
if(i > 1) // prendo le scommesse dell'accoppiata
{
sA = document.getElementById("bet"+(i+1) + "_a").value;
gioco.scommesseA[i-2] = Number(sA);
totScommesse += gioco.scommesseA[i-2];
}
var s = document.getElementById("bet"+(i+1)).value; // scommesse vincitore
gioco.scommesseW[i] = Number(s);
totScommesse += gioco.scommesseW[i];
}
if(totScommesse > gioco.monete)
window.alert("Scommessa non valida...\nNon sei così ricco!!");
else
{
gioco.monete -= Number(totScommesse);
document.getElementById("monete").innerText = "";
document.getElementById("monete").innerText = gioco.monete;
chiudi_popup_scommesse();
}
if(gioco.logged == true)
SalvataggioDati();
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.1.7
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 22, 2021 alle 10:44
-- Versione del server: 8.0.21
-- PHP Version: 5.6.40
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `my_betspritesrace`
--
-- --------------------------------------------------------
--
-- Struttura della tabella `corridore`
--
CREATE TABLE IF NOT EXISTS `corridore` (
`nome` varchar(100) NOT NULL,
`vittorie` int NOT NULL,
`2posto` int NOT NULL,
`3posto` int NOT NULL,
`punteggio` int NOT NULL,
PRIMARY KEY (`nome`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dump dei dati per la tabella `corridore`
--
INSERT INTO `corridore` (`nome`, `vittorie`, `2posto`, `3posto`, `punteggio`) VALUES
('Avatar Punk', 21, 33, 34, 163),
('<NAME>', 25, 23, 28, 149),
('Jonny', 32, 27, 29, 179),
('<NAME>', 38, 28, 18, 188),
('<NAME>', 17, 25, 34, 135),
('V<NAME>', 33, 30, 23, 182);
-- --------------------------------------------------------
--
-- Struttura della tabella `utente`
--
CREATE TABLE IF NOT EXISTS `utente` (
`username` varchar(50) NOT NULL,
`password` varchar(200) NOT NULL,
`email` varchar(100) DEFAULT NULL,
`monete` double NOT NULL,
`tempoGioco` int DEFAULT '0',
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dump dei dati per la tabella `utente`
--
INSERT INTO `utente` (`username`, `password`, `email`, `monete`, `tempoGioco`) VALUES
('aaa', '$2y$10$fSS7DP9MBG/kYNxVJvuvNuFHIE7QYFXTQvPktWAApxOGTzwlk8twe', '', 10, 0),
('aaaaaaaaaa', '$2y$10$PBVJasP4lbNeoTeYPAmXzeBSpp20glwyzZjnTWkrk05k2YWDWa/c2', 'a@a', 10, 0),
('adghfh', '$2y$10$pRfspowt3rk8emGsEEXyc.I4yFA62csJRktQ8svbAoyXEjWv0mBdm', '<EMAIL>', 10, 0),
('ale', '$2y$10$JofJw/TOLTpAUCfOS/U2me0poHxu1k0goe6c392CT7SaLAXZvxdE6', '', 9, 3),
('altervista', '$2y$10$QTtJ6QcIyko/Qtl7UMhEluCtDG0rFbZmH6BN2xCwowsYmKw9NTGnK', '', 77.13, 10),
('Andre', '$2y$10$PhFVBUKIjvzGW1J3OLUMFOCI46/Q2Fe9pmyT7bXaOlXraXlgE0vh.', '', 42.22, 4),
('Angelo', '$2y$10$gi91gEKJ8yekURuI4vG1UuOvbPfu5ud2onIjQkmuT5TBoqypaVeGa', '', 16, 1),
('Anto', '$2y$10$u8euCsOmOIzmBpkRvQJ8eesE7BK4rOBJ/VBeI2swce9aQwktUF3zq', '', 10, 0),
('bbbb', '$2y$10$b7hRq4PwtPFrD2ehKBMl6.TIpxe7wddT3OXD/C0flaZUSMyDS0sHS', '<EMAIL>', 15, 0),
('bla', '$2y$10$keooX.Xi7t5YRxKKGIe9HeFXrURrW8FO7gnNv8EPPdyVnJvk.hjju', 'bla@bla', 10, 0),
('censored1', '$2y$10$6mfBAT2a7rd8yWsh7VA7HOcvoHuRc3NP7oFYU.eioCAAHl7m/Kfeu', '', 21, 1),
('Chris99', '$2y$10$tBLiYGriddrzIMhpQxjovO/qsyCyE/DFsOcCpfky7F1lzbq8kHNv.', '', 10, 0),
('ciao', '$2y$10$4qMCrWYicJ4D.ydyf9NK6OrBlmQHMtmmNLjG1kOzqumhYXiWhnKvq', '', 15, 0),
('Cugi', '$2y$10$hpk/l6cQz6qBvK9tui8mf.8f02MDKO/ILHj1JUzIC3pBOjoILgrJq', '', 750, 24),
('darione', '$2y$10$.r5jjycx1sgjPaTYYrZ9CuhzCgR/wXaFDyMh1Wp0QsnPMmXE4u8Be', '<EMAIL>', 10, 0),
('dhdh', '$2y$10$jxmi7mkF.TStBxtCuK2m6u.YuR1rmswy47g1obHVYKFj9osQIKbgW', '', 10, 0),
('Driveights', '$2y$10$4Xmf3/Qb5Vrz25tz9Jw8iem6ODbJlaEUWE2UGkmsLEFcnQI6GYeyK', '<EMAIL>', 10, 0),
('EvilStea', '$2y$10$OLmi.dYl.5BYhwBvxAKgi.r17ebQgLu/fMDv304ChZuCMOXtNZW42', '', 3400.8, 1),
('gabriele', '$2y$10$h.5xANwM0a1PHztRo1cAaOnOTpUIEStsmYZmMK9aRHC3jK3G70Ru2', '<EMAIL>', 10, 0),
('Gg1', '$2y$10$Vkv13QFKvoyC3SngIn5d/uFv995FOpi0Hsx0K4dzmeIpMDlyDNYgK', '', 21, 1),
('Giuliobello', '$2y$10$/YlcpE5h6X/6.V.NyhRAl.QnnD4gXqQnBei5cmGKhj610IXGvpcG6', '', 5, 1),
('giuliopedemonte', '$2y$10$FFg0H8PnvonT1MnoqwZBSuAR8RG2Ja2hn3.5VoLnX7ZqhrWLZ42iu', '<EMAIL>', 10, 0),
('GM8601', '$2y$10$L.fuf5WGx6boyTyF2ytsWeivjdBKhwe0u2LG7rn9z.s23sSmNc5xm', '', 16, 0),
('gs__', '$2y$10$dFbadgPlWpbibZE21.Xhd.SRF4ZA//xJaISrnnS/K/j4g0ePlf5Ua', '', 12, 0),
('hello', '$2y$10$kQD5sVS6Jov2JX5QIHdTh..Pg75viPBxZX8hv3zmQkUsON7LVHwiq', '', 1782.05, 11),
('iack', '$2y$10$AllxF9VQmCdeD6G3GbJ2oey4Meau9WtHkyvVJ8fXW4tkQlwlyLzhq', '<EMAIL>', 21.71, 1),
('Jacopo00', '$2y$10$Hc098l3o7uCw0LLwtPZse.P11gwcfOwCA3IYjzTxTnWkap/JZ5XNW', '', 14, 0),
('Luca', '$2y$10$SaEXuN5pZVJHboiOmMmDke3Vv0DvIODcptmLXtjwjRkh8bUINTn4a', '<EMAIL>', 16, 0),
('marco', '$2y$10$SDKISUlXOXO71yEpOI8NpOCzJ46P91gEYSm2FKPOcw.6VUVxn8KZe', '', 11.240000000000002, 4),
('matte', '$2y$10$yoj/.49RBagjP4l1Rc5Ab.GOLpN/obanbGHO1EiYGGPSQ1nSxJ74u', '', 653, 28),
('Pietro', '$2y$10$xcg/Fv5w2YNGgCYtflXP1O5ZgkScueDKJR9glFaW9gSCvjYkEDm6q', '', 18, 0),
('pippo', '$2y$10$IfhW40kzlUNNiZoPL4AYa.iSZ8//70MU1bl4V6NKCuvtKHnNIAojG', '', 10, 0),
('Pippo1234', '$2y$10$148Jl0s3PcmGgiiyBafXNOJtfUrgXgtV2c8GmuCQ3HamzcFvqhq9y', '', 10, 0),
('pippoFranco', '$2y$10$pi2x236yltH0tP.n9lXPpu8h1mbW70RG0vQ2wpAZ1c.PzBjfn1WYm', '', 11, 2),
('prova', '$2y$10$S7noHkxJq0QXCi66QbFdoergw/v939kqp8MxEqhZVshWe99DEUZQG', '', 83.06, 21),
('prova1234', '$2y$10$79SeW7E1NSe8GCT/RYzGrO7Ui0mtvbos/fvVBaX3lmG4OFBA7bma.', '<EMAIL>', 1, 0),
('sasso', '$2y$10$4i.p479HC7Eg/8ERLpFyue95sFgZxvBEvO5XUbZOIcT92bH9vnlP2', '', 16, 0),
('Seghino', '$2y$10$SGb3uIFh4TaxuGVP290zZ.L3v8JwkPrA9.oNc9WdOSDhq4nyVFgku', '', 21, 5),
('test', '$2y$10$p1Sck4BEyegwP1MqWa6DV.CdtbcmsOou.JQxng2tg3GAcM0pyfSWy', '', 777, 83),
('test2222', '$2y$10$mpgyc8ZAT.X.qsfR9NbDV.cD.6berIWXqH8DR7C/kTIzSD4dMrw9S', '<EMAIL>', 13, 0),
('testt', '$2y$10$lT8rRzMOEnqpuLBrnstZZ.W5gj/jbSWgNUfTXam/DuTSDEWxusat.', '<EMAIL>', 11, 0),
('Tonino', '$2y$10$QvJx6ZVy2qroSDMpR0XUXu9PY286dp7N3iO3SPGJ91eddDOwRUe5W', '', 10, 0),
('topolino', '$2y$10$S2Ppc4QU9ez1BL8sbeZhv.AQx.Ozon5Xpmmm7aVLWpT6b.tp0MtOi', '', 43, 2),
('Voldemort82', '$2y$10$mbBWq1duGEpJJDutwSdWTeyrr8OPX0PqPTxku.K.Oqvc7lzatcqS6', '', 82, 7),
('Zzz', '$2y$10$j80A4XRUFPKcrqbggtbeqeg/hN/mIj75VF39KkGW4sAjDLz6uulWa', '', 9, 1);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
include 'db_info.php';
session_start();
$classifica = array();
$query = "SELECT username, monete, tempoGioco FROM utente ORDER BY monete DESC";
$result = $con->query($query);
$i = 0;
while($row = $result->fetch_array())
{
$utente = array();
$classifica[$i] = $row['username'];
$i++;
$classifica[$i] = round($row['monete']);
$i++;
$classifica[$i] = $row['tempoGioco'];
$i++;
}
// '{}'
print json_encode($classifica);
?>
| 44927d1e21fcaaf7790879dfd28c0fb6a1594747 | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 18 | PHP | mattebernini/BetspritesRace | c57b41831f8c25adead7644dde77971f4b6a21e4 | 3de8467ab25cc95c4ce8d0a1d66a4dcd00a97939 |
refs/heads/master | <file_sep>namespace Asteroids
{
public interface IPool
{
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Asteroids
{
public static class PoolServiceLocator
{
private static readonly Dictionary<Type, object> _poolContainer = new Dictionary<Type, object>();
public static void SetPool<T>(T pool) where T : IPool
{
// не понял, зачем тут нужна проверка на наличие в словаре ключа? если нет - добавит, если есть - передобавит
// или это из соображений производительности?
_poolContainer[typeof(T)] = pool;
}
public static T Resolve<T>()
{
// переделал твою реализацию проверки наличия ключа на TryGetValue
// вроде бы под капотом делает то же самое
_poolContainer.TryGetValue(typeof(T), out var pool);
return (T) pool;
}
}
} | b8ae8d55186f77ac6acf33a314e6a76d6bb56ea9 | [
"C#"
] | 2 | C# | EdrenBaton/UnityLearning4_Lesson5 | 19da5a8df2684179ee93c2dcba7052aa22b93958 | 9dde1deed5ca2ca310b4594688367b2ab56578a6 |
refs/heads/master | <file_sep># yoovies
### 영화, TV프로그램 정보소개 앱
- React Native, Expo, iOS, Android 사용
- 노마드 코더의 "초보를 위한 React Native" 강의 클론코딩
- 노마드 코더 강의 결과물 구경하기
- https://noovies.netlify.com/<file_sep>import TvContainer from "./TvContainer";
export default TvContainer;
// export { Container from "./TvContainer" } as default; | 6aac9c05f70e4daa58fc3fc02e4280ce72a6fe1f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mango13/yoovies | 3233a0d590147b3ad5bd75581dded6af1eecdf4d | 504a2762a7eaaf6b1b7ec5fe8425b246f2341f6c |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
public class RangedEnemyAttack : MonoBehaviour
{
public float timeBetweenAttacks = 3.0f; // The time in seconds between each attack.
public int attackDamage = 10; // The amount of health taken away per attack.
public float playerDistance; //testing now
public Transform playert; //testing now
public Transform tt; //testing now
Animator anim; // Reference to the animator component.
GameObject player; // Reference to the player GameObject.
PlayerHealth playerHealth; // Reference to the player's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
bool playerInRange; // Whether player is within the trigger collider and can be attacked.
float timer; // Timer for counting up to the next attack.
//
public GameObject StoneProjectilePrefab;
//private GameObject _StoneProjectile;
public Transform ProjectileSpawn;
//public float obstacleRange = 5.0f;
void Awake ()
{
// Setting up the references.
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent<EnemyHealth>();
anim = GetComponent <Animator> ();
//
tt = this.transform;
playert = GameObject.FindGameObjectWithTag("Player").transform;
}
/*void OnTriggerEnter (Collider other)
{
// If the entering collider is the player...
if(other.gameObject == player)
{
// ... the player is in range.
playerInRange = true;
//anim.SetBool ("InAttackRange", playerInRange);
///
//Fire();
/*Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hit;
if (Physics.SphereCast (ray, 0.75f, out hit)) {
GameObject hitObject = hit.transform.gameObject;
if (hitObject.GetComponent<PlayerHealth> ()) {
if (_StoneProjectile == null) {
_StoneProjectile = Instantiate (StoneProjectilePrefab) as GameObject;
_StoneProjectile.transform.position = transform.TransformPoint (Vector3.forward * 1.5f);
_StoneProjectile.transform.rotation = transform.rotation;
}
} else if (hit.distance < obstacleRange) {
float angle = Random.Range (-110, 110);
transform.Rotate (0, angle, 0);
}
}
}
}
void OnTriggerExit (Collider other)
{
// If the exiting collider is the player...
if(other.gameObject == player)
{
// ... the player is no longer in range.
playerInRange = false;
anim.SetBool ("InAttackRange", playerInRange);
}
} */
void Update ()
{
//
playerDistance = Vector3.Distance(tt.position, playert.position);
if (playerDistance <= 12f)
{
playerInRange = true;
}
if (playerDistance > 12f)
{
playerInRange = false;
}
//
// Add the time since Update was last called to the timer.
timer += Time.deltaTime;
// If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
{
// ... attack.
//anim.SetBool ("InAttackRange", playerInRange);
anim.SetTrigger ("InRange");
Fire(); //testing
Attack ();
}
// If the player has zero or less health...
if(playerHealth.currentHealth <= 0)
{
// ... tell the animator the player is dead.
anim.SetTrigger ("PlayerDead");
}
}
void Attack ()
{
// Reset the timer.
timer = 0f;
// If the player has health to lose...
if(playerHealth.currentHealth > 0 && enemyHealth.currentHealth > 0)
{
// ... damage the player.
playerHealth.TakeDamage (attackDamage);
}
}
void Fire()
{
// Create the Bullet from the Bullet Prefab
var bullet = (GameObject)Instantiate (
StoneProjectilePrefab,
ProjectileSpawn.position,
ProjectileSpawn.rotation);
// Add velocity to the bullet
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 40;
// Destroy the bullet after 2 seconds
Destroy(bullet, 2.0f);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(menuName = "Flexible UI Data")]
public class FlexibleUIData : ScriptableObject
{
public Sprite buttonSprite;
public SpriteState buttonSpriteState;
public Font m_font;
public int m_fontsize;
public Color textColor;
public TextAnchor m_Alignment;
public bool m_alignByText;
public HorizontalWrapMode horizontalOverflow;
public VerticalWrapMode verticalOverflow;
}
<file_sep>using UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour
{
public GameObject FirstPersonCamera;
public GameObject ThirdPersonCamera;
public GameObject crosshair;
public bool viewIsThird = true;
void Start ()
{
//FirstPersonCamera.gameObject.SetActive(false);
FirstPersonCamera.gameObject.SetActive(true);
ThirdPersonCamera.gameObject.SetActive(true);
crosshair.gameObject.SetActive(false);
//viewIsThird = true;
if (!viewIsThird) {
FirstPersonCamera.gameObject.SetActive(true);
ThirdPersonCamera.gameObject.SetActive(false);
crosshair.gameObject.SetActive(true);
Cursor.visible = false;
}
else {
FirstPersonCamera.gameObject.SetActive(false);
ThirdPersonCamera.gameObject.SetActive(true);
crosshair.gameObject.SetActive(false);
}
}
void Update ()
{
if (PlayerHealth.isDead) {return;}
if (viewIsThird) { Cursor.visible = true; }
if (Input.GetKeyDown(KeyCode.T)) {
if (viewIsThird) {
FirstPersonCamera.gameObject.SetActive(true);
ThirdPersonCamera.gameObject.SetActive(false);
crosshair.gameObject.SetActive(true);
Cursor.visible = false;
}
else {
FirstPersonCamera.gameObject.SetActive(false);
ThirdPersonCamera.gameObject.SetActive(true);
crosshair.gameObject.SetActive(false);
}
viewIsThird = !viewIsThird;
}
}
}
<file_sep># Unity-ProcederalEnvironment
auto generate procedural scripts
This game's environment is auto generated at run time using map generator
and mesh generator. By using the runtime navmesh APIs from Unity, the AI agent
now navigate the new space without manual baking.
## screenshot

<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public static int nextPerk;
int nextPerkInTime;
bool playerHasPerk = false;
//public GameObject locator;
//used to call a perk function
public static Dictionary<int, System.Action> perks = new Dictionary<int, System.Action>();
// add perk functions to dict
public AudioClip regBullet;
public AudioClip fastBullet;
public AudioClip cannonBullet;
//public AudioSource youWinSX;
public bool isFirstPerson = false;
public PlayerHealth playerHealth;
public PlayerShooting playerShooting;
public PlayerMovement playerMovement;
public GameObject enemyFast;
public GameObject enemyTank;
public GameObject enemyReg;
public GameObject enemyRanged;
public GameObject perk3D;
public static GameObject clone = null;
public List<GameObject> enemies = new List<GameObject>(); //create list of enemies to spawn for each wave
public float spawnTime = 3f;
public Transform[] spawnPoints;
public int currentLevel; // The current level.
public int currentWave; // The current wave.
public static int foesLeft; // Foes Left to defeat before wave ends.
public Text infoText; // Reference to the Text component for level, wave, foes left.
public Text waveClearText; // Reference to the Text component for wave cleared text.
public Text perkText; // Reference to the Text component for perk text.
/*
total enemies for wave 0 through N
*/
//public static int[] waves = new int[] {0, 15, 30, 50};
// wave # {0, 1, 2, 3, 4, 5, 6,}
public static int[] fastEnemyWaves = new int[] {0, 0, 0, 5, 0, 3};
public static int[] tankEnemyWaves = new int[] {0, 0, 2, 0, 0, 1};
public static int[] regEnemyWaves = new int[] {0, 3, 3, 0, 4, 3};
public static int[] rangedEnemyWaves = new int[] {0, 0, 0, 0, 2, 1};
/* For testing purposes
public static int[] fastEnemyWaves = new int[] {0, 0};
public static int[] tankEnemyWaves = new int[] {0, 0};
public static int[] regEnemyWaves = new int[] {0, 1};
public static int[] rangedEnemyWaves = new int[] {0, 0};
*/
public int finalWave;
float timeRemaining = -1;
int perkTime = 10; // duration of perk
void Start(){
timeRemaining = -1;
}
public void beginGame ()
{
finalWave = regEnemyWaves.Length - 1;
//finalWave = 1;
//youWinSX = GetComponent <AudioSource> ();
playerHealth = GetComponentInChildren <PlayerHealth> ();
playerShooting = GetComponentInChildren <PlayerShooting> ();
playerMovement = GetComponentInChildren <PlayerMovement> ();
// Set up the reference.
//infoText = GetComponentInChildren <Text> ();
infoText.text = "";
waveClearText.text = "";
perkText.text = "";
perks.Clear();
perks.Add(0, FullHealthPerk);
perks.Add(1, FastMovementPerk);
perks.Add(2, RapidFirePerk);
perks.Add(3, InstantKillPerk);
//when game starts, start on level 1 wave 1, create list of enemy game objects
timeRemaining = 5;
SetLevel(1);
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
if (sceneName == "level3") {
SetLevel(2);
}
else if (sceneName == "level5") {
SetLevel(3);
}
SetWave(1);
CreateEnemyList();
Spawn ();
}
// picks a random perk to spawn at a random time at a random spawn point
void RandomizePerk(){
nextPerk = Random.Range(0, 4); //perk type
nextPerkInTime = Random.Range(10, 60); //how often perk spawns
Invoke("SpawnPerk", nextPerkInTime); //spawn perk after time
}
//init list of enemy objects for spawn on each wave
void CreateEnemyList() {
Debug.Log(currentLevel);
Debug.Log(regEnemyWaves[currentWave] * currentLevel);
enemies.Clear();
for (int i = 0; i < fastEnemyWaves[currentWave] * currentLevel; i++) {
enemies.Add(enemyFast);
}
for (int i = 0; i < regEnemyWaves[currentWave] * currentLevel; i++) {
Debug.Log(i);
enemies.Add(enemyReg);
}
for (int i = 0; i < tankEnemyWaves[currentWave] * currentLevel; i++) {
enemies.Add(enemyTank);
}
for (int i = 0; i < rangedEnemyWaves[currentWave] * currentLevel; i++) {
enemies.Add(enemyRanged);
}
}
void SetLevel(int level) {
currentLevel = level;
}
void SetWave(int wave) {
currentWave = wave;
foesLeft = fastEnemyWaves[currentWave] * currentLevel + regEnemyWaves[currentWave] * currentLevel + tankEnemyWaves[currentWave] * currentLevel + rangedEnemyWaves[currentWave] * currentLevel;
RandomizePerk(); // picks a random perk to spawn at a random time at a random spawn point
}
public static void SetPerk() {
perks[nextPerk]();
//RemovePerk();
}
void DisableFastMovementPerk() {
playerHasPerk = false;
perkText.text = "";
playerMovement.changeMovementSpeed(7f);
}
// call this when player picks up fast movement perk
void FastMovementPerk() {
playerHasPerk = true;
Debug.Log("Fast Speed");
perkText.text = "Increased Speed";
playerMovement.changeMovementSpeed(20f);
Invoke("DisableFastMovementPerk", perkTime);
}
//
// call this when player picks up full health perk
void FullHealthPerk() {
playerHasPerk = true;
Debug.Log("Full Health");
perkText.text = "Full Health";
playerHealth.fullHealth();
Invoke("RemoveFullHealthText", 4);
}
void RemoveFullHealthText() {
playerHasPerk = false;
perkText.text = "";
}
// call this when resetting fire rate
void DisableRapidFirePerk() {
playerHasPerk = false;
perkText.text = "";
playerShooting.updateShootSpeed(.15f);
playerShooting.switchGunAudio(regBullet);
}
// call this when player picks up rapid fire perk
void RapidFirePerk() {
playerHasPerk = true;
Debug.Log("Rapid Fire");
perkText.text = "Rapid Fire";
playerShooting.updateShootSpeed(.07f);
playerShooting.switchGunAudio(fastBullet);
Invoke("DisableRapidFirePerk", perkTime);
}
// disables instant kill perk
void DisableInstantKillPerk(){
playerHasPerk = false;
perkText.text = "";
playerShooting.updateDamage(20);
playerShooting.updateShootSpeed(.15f);
playerShooting.switchGunAudio(regBullet);
}
// call this when player picks up instant kill perk
void InstantKillPerk() {
playerHasPerk = true;
Debug.Log("Instant Kill");
perkText.text = "Instant Kill";
playerShooting.updateDamage(1000);
playerShooting.updateShootSpeed(.50f);
playerShooting.switchGunAudio(cannonBullet);
Invoke("DisableInstantKillPerk", perkTime);
}
void LoadEndGame(){
Cursor.visible = true;
SceneManager.LoadScene ("WinScreen"); //testing now
}
void Update ()
{
if (foesLeft < 1 && currentWave != finalWave) {
if (timeRemaining >= 0) { //counts down from 10 to 0
timeRemaining -= Time.deltaTime;
waveClearText.text = "Wave Cleared! New Waves Spawning In: " + timeRemaining.ToString ("f0");
}
else {
waveClearText.text = "";
timeRemaining = 5;
SetWave(currentWave + 1);
CreateEnemyList();
Spawn ();
}
}
infoText.text = "Level: " + currentLevel + "\nWave: " + currentWave + "\nFoes: " + foesLeft;
if (currentWave == finalWave && foesLeft < 1) {
if (currentLevel == 3) {
LoadEndGame();
}
else if (currentLevel == 2) {
Cursor.visible = true;
SceneManager.LoadScene ("TwoToThreeScreen"); //testing now
//currentLevel = 3;
}
else {
Cursor.visible = true;
SceneManager.LoadScene ("OneToTwoScreen"); //testing now
//currentLevel = 2;
}
}
}
static int maxl = 8;
int[,] spawnzone = new int[maxl,maxl];
Vector3 returnSpawnZone(){
int i = Random.Range(0,maxl);
int j = Random.Range(0,maxl);
while (spawnzone[i,j]==1) {
i = Random.Range(0,maxl);
j = Random.Range(0,maxl);
}
spawnzone[i,j] = 1;
Vector3 r = new Vector3(i-maxl/2, 0, j-maxl/2);
return r;
}
Vector3 returnHeight(Vector3 pos){
//locator.transform.position = pos+returnSpawnZone();
Vector3 tmp = pos+returnSpawnZone();
RaycastHit hit;
if (Physics.Raycast(tmp+Vector3.up*10, Vector3.down, out hit, 100f)){
//Debug.Log(hit.point);
return hit.point;
}
return tmp;
}
void Spawn()
{
int spawnPointIndex;
for (int i = 0; i < foesLeft; i++) {
spawnPointIndex = Random.Range(0, spawnPoints.Length);
//this is a Transform, each Transform has a position and rotation
Instantiate (enemies[i], returnHeight(spawnPoints[spawnPointIndex].position), spawnPoints[spawnPointIndex].rotation);
}
spawnzone = new int[maxl,maxl];
}
void SpawnPerk() {
//Debug.Log("attempting to spawn PERK");
//make sure there isn't already a perk out and player doesn't have a perk currently
if (clone == null && !playerHasPerk) {
int spawnPointIndex;
spawnPointIndex = Random.Range(0, spawnPoints.Length);
clone = Instantiate (perk3D, spawnPoints[spawnPointIndex].position, perk3D.transform.rotation);
//Debug.Log("SPAWNING PERK");
Invoke("RemovePerk", 15); // destroy perk after 15 s
}
}
// removes game object for perk
void RemovePerk() {
//Debug.Log("REMOVING PERK");
if (clone != null) {
Destroy(clone, 0f);
clone = null;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class FirstPerson: MonoBehaviour
{
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity = 1.0f;
public float smoothing = 2.0f;
public float speed = 5.0f;
GameObject character;
void Start(){
//Cursor.lockState = CursorLockMode.Locked; //disables cursor showing up, implement later
character = this.transform.parent.gameObject;
}
void Update() {
if (Time.timeScale != 0 && !PlayerHealth.isDead) { //game is paused
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f/smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f/smoothing);
mouseLook += smoothV;
//transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
//character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
Quaternion target = Quaternion.AngleAxis(mouseLook.x, character.transform.up);
character.transform.localRotation = Quaternion.Slerp(character.transform.localRotation, target, speed*Time.deltaTime);
}
/*
if (Input.GetKeyDown("T")) { //switching back to 3rd person show cursor
Cursor.lockState = CursorLockMode.None;
}
*/
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class PauseManager : MonoBehaviour {
GameObject pauseObjects;
GameObject confirmRestartObjects;
GameObject confirmQuitObjects;
GameObject gameOverObjects;
// Use this for initialization
void Start () {
Time.timeScale = 1;
//pauseObjects = GameObject.FindGameObjectsWithTag("ShowOnPause");
pauseObjects = GameObject.FindWithTag("ShowOnPause");
confirmRestartObjects = GameObject.FindWithTag("ConfirmRestart");
confirmQuitObjects = GameObject.FindWithTag("ConfirmQuit");
gameOverObjects = GameObject.FindWithTag("ShowOnGameOver");
hideAll();
}
// Update is called once per frame
void Update () {
//uses the p button to pause and unpause the game
if(Input.GetKeyDown(KeyCode.P))
{
pauseControl();
}
}
//controls the pausing of the scene
public void pauseControl(){
if (PlayerHealth.isDead) {return;}
if(Time.timeScale == 1)
{
Time.timeScale = 0;
Cursor.visible = true;
showPaused();
} else if (Time.timeScale == 0){
Time.timeScale = 1;
Cursor.visible = false;
hideAll();
}
}
//hides all possible pause objects
public void hideAll(){
pauseObjects.SetActive(false);
confirmRestartObjects .SetActive(false);
confirmQuitObjects.SetActive(false);
gameOverObjects.SetActive(false);
}
//shows objects with ShowOnPause tag
public void showPaused(){
hideAll();
pauseObjects.SetActive(true);
}
//shows confirm restart menu
public void showConfirmRestart(){
hideAll();
confirmRestartObjects.SetActive(true);
}
//shows confirm quit menu
public void showConfirmQuit(){
hideAll();
confirmQuitObjects.SetActive(true);
}
//shows game over menu
public void showGameOver(){
hideAll();
Cursor.visible = true;
gameOverObjects.SetActive(true);
}
//Restarts the current Level
public void Restart(){
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
if (sceneName == "level3") {
SceneManager.LoadScene (3);
} else if (sceneName == "level5") {
SceneManager.LoadScene (5);
} else {
SceneManager.LoadScene (1);
}
}
// go to main menu
public void ExitToMain(){
SceneManager.LoadScene(0);
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class quitScene : MonoBehaviour {
public Button quitButton;
void Start()
{
//Button btn = quitButton.GetComponent<Button>();
quitButton.onClick.AddListener( delegate() {Quit();});
}
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit ();
#endif
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshGenerator : MonoBehaviour {
public SquareMap sq;
public MeshFilter walls;
public MeshFilter floor;
public float wallHeight = 5;
/* vertices and triangles needed for mesh generation */
List<Vector3> vertices;
List<int> triangles;
/*
* Mesh helper data structures for checking outline */
List<List<int>> outlines = new List<List<int>>();
HashSet<int> checkedList = new HashSet<int>();
Dictionary<int,List<Triangle>> tD = new Dictionary<int,List<Triangle>>();
MeshCollider wallCollider;
int newWallMesh= 0;
MeshCollider wallCollider2;
/*
* Genereate the floor mesh using the randomly generate map
* and create the vertical wall
*/
public void GenerateMesh(int[,] map, float squareSize){
outlines.Clear();
checkedList.Clear();
tD.Clear();
sq = new SquareMap(map, squareSize);
vertices = new List<Vector3>();
triangles = new List<int>();
for(int x = 0; x < sq.squares.GetLength(0); x++){
for(int y=0; y < sq.squares.GetLength(1); y++){
TrigulateSquare(sq.squares[x,y]);
}
}
Mesh mesh = new Mesh();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
floor.mesh = mesh;
createWallMesh();
}
/*
* For each vertice in the outline, create a square
* and create two triangles for each square.
*/
void createWallMesh(){
calculateMesh(); // generate floor mesh and outlines list
/* Mesh components
* wv -- wall vertices
* wt -- wall triangles
*/
List<Vector3> wv = new List<Vector3>();
List<int> wt = new List<int>();
foreach(List<int> outline in outlines){
for(int i =0; i < outline.Count-1; i++){
int start = wv.Count;
//create 4 vertices for each outline vertex
wv.Add(vertices[outline[i]]); //vertex i
wv.Add(vertices[outline[i+1]]);//vertex i +1
wv.Add(vertices[outline[i]]-Vector3.up*wallHeight);//vertex i at wall height
wv.Add(vertices[outline[i+1]]-Vector3.up*wallHeight);//vertext i+1 at wall height
//triangle 1
wt.Add(start+0);
wt.Add(start+2);
wt.Add(start+3);
//Triangle 2
wt.Add(start+3);
wt.Add(start+1);
wt.Add(start+0);
}
}
Mesh wallMesh = new Mesh();
wallMesh.vertices = wv.ToArray();
wallMesh.triangles = wt.ToArray();
walls.mesh = wallMesh;
// bool flag used to add component if needed
if (newWallMesh==0){
wallCollider2 = walls.gameObject.AddComponent<MeshCollider>();
newWallMesh=1;
}
wallCollider2.sharedMesh=wallMesh;
}
/* Trianglulate the following square configuration
* * - *
* - -
* * - *
* There are 4 main control nodes for a total of 16 different
* combinations/configrations.
*
* all Triangles vertices are selected in clock-wise direction
*
* case values corresponde to the 4 states of the control nodes
* x - 8
* x - 4
* x - 2
* x - 1
*
*/
void TrigulateSquare(Square s){
switch(s.config){
case 0:
break;
case 1:
MeshFromPoints(s.midLeft, s.midBottom, s.bottomLeft);
break;
case 2:
MeshFromPoints(s.bottomRight, s.midBottom, s.midRight);
break;
case 4:
MeshFromPoints(s.topRight, s.midRight, s.midTop);
break;
case 8:
MeshFromPoints(s.topLeft, s.midTop, s.midLeft);
break;
case 3:
MeshFromPoints(s.midRight, s.bottomRight, s.bottomLeft, s.midLeft);
break;
case 6:
MeshFromPoints(s.midTop, s.topRight, s.bottomRight, s.midBottom);
break;
case 9:
MeshFromPoints(s.topLeft, s.midTop, s.midBottom, s.bottomLeft);
break;
case 12:
MeshFromPoints(s.topLeft, s.topRight, s.midRight, s.midLeft);
break;
case 5:
MeshFromPoints(s.midTop, s.topRight, s.midRight, s.midBottom, s.bottomLeft, s.midLeft);
break;
case 10:
MeshFromPoints(s.topLeft, s.midTop, s.midRight, s.bottomRight, s.midBottom, s.midLeft);
break;
case 7:
MeshFromPoints(s.midTop, s.topRight, s.bottomRight, s.bottomLeft, s.midLeft);
break;
case 11:
MeshFromPoints(s.topLeft, s.midTop, s.midRight, s.bottomRight, s.bottomLeft);
break;
case 13:
MeshFromPoints(s.topLeft, s.topRight, s.midRight, s.midBottom, s.bottomLeft);
break;
case 14:
MeshFromPoints(s.topLeft, s.topRight, s.bottomRight, s.midBottom, s.midLeft);
break;
case 15:
MeshFromPoints(s.topLeft, s.topRight, s.bottomRight, s.bottomLeft);
break;
}
}
/*
* In a close-wise fashion, create all the triangles from
* the points array
*/
void MeshFromPoints(params Node[] points){
assignVertices(points);
if (points.Length >= 3)
createTriangle(points[0], points[1], points[2]);
if (points.Length >= 4)
createTriangle(points[0], points[2], points[3]);
if (points.Length >= 5)
createTriangle(points[0], points[3], points[4]);
if (points.Length >= 6)
createTriangle(points[0], points[4], points[5]);
}
/*
* Add point position to the vertices array
* and assign an index id to track each point
*/
void assignVertices(Node[] points){
for(int i = 0; i < points.Length; i++){
if (points[i].index == -1){
points[i].index = vertices.Count;
vertices.Add(points[i].position);
}
}
}
/*
* add points to the triangles array
* create triangle using the 3 points
* link the triangle to its correspoding points
* so that its possible to check if they belong to the same triangle.
*/
void createTriangle(Node a, Node b, Node c){
triangles.Add(a.index);
triangles.Add(b.index);
triangles.Add(c.index);
Triangle triangle = new Triangle (a.index, b.index, c.index);
addToDict(triangle.indexA, triangle);
addToDict(triangle.indexB, triangle);
addToDict(triangle.indexC, triangle);
}
/*
* Goes through each point and check all the triangles it belong
* to and return a valid outline vertex if found.
*/
int getNext(int vertex){
List<Triangle> container = tD[vertex];
for (int i = 0; i < container.Count; i++){
Triangle triangle = container[i];
for(int j = 0; j < 3; j++){
int next = triangle[j];
if (next != vertex && !checkedList.Contains(next)){
if (isOutline(vertex, next)){
return next;
}
}
}
}
return -1;
}
/*
* Recursively follow each vertice points and
* get groups of outline points
* that forms the outline edges.
*/
void calculateMesh(){
for(int index = 0; index < vertices.Count; index++){
if (!checkedList.Contains(index)){
int newV = getNext(index);
if (newV != -1){
checkedList.Add(index);
List<int> newOutline = new List<int>();
newOutline.Add(index);
outlines.Add(newOutline);
followNext(newV, outlines.Count-1);
outlines[outlines.Count-1].Add(index);
}
}
}
}
/* Recursive helper function */
void followNext(int index, int outlineIndex){
outlines[outlineIndex].Add(index);
checkedList.Add(index);
int nextindex = getNext(index);
if (nextindex != -1 ){
followNext(nextindex, outlineIndex);
}
}
/* check if two vertices belong to the same triangle group or not */
bool isOutline(int vertexA, int vertexB){
List<Triangle> containsA = tD[vertexA];
int shared = 0;
for (int i = 0; i < containsA.Count; i++){
if (containsA[i].Contains(vertexB)) {
shared++;
if (shared > 1) {break;}
}
}
return shared == 1;
}
/* Triangle struct to track its 3 vertices */
struct Triangle{
public int indexA;
public int indexB;
public int indexC;
int[] vertices;
public Triangle(int a, int b, int c){
indexA = a;
indexB = b;
indexC = c;
vertices = new int[3];
vertices[0] = a;
vertices[1] = b;
vertices[2] = c;
}
public int this[int i]{
get {
return vertices[i];
}
}
public bool Contains(int index){
return index==indexA || index==indexB || index ==indexC;
}
}
/* link each triangle to its vertices
* A vertex can be connected to a list of triangles
* and must be checked.
*/
void addToDict(int indexKey, Triangle triangle){
if (tD.ContainsKey(indexKey)){
tD[indexKey].Add(triangle);
} else {
List<Triangle> triList = new List<Triangle>();
triList.Add(triangle);
tD.Add(indexKey, triList);
}
}
/*
* Use the randomly generated map,
* create the square for each point that are true/on
*/
public class SquareMap{
public Square[,] squares;
public SquareMap(int[,] map, float squareSize){
int nodeCountX = map.GetLength(0);
int nodeCountY = map.GetLength(1);
float mapWidth = nodeCountX*squareSize;
float mapHeight = nodeCountY*squareSize;
ControlNode[,] controlNodes = new ControlNode[nodeCountX, nodeCountY];
for (int x = 0; x < nodeCountX; x++){
for(int y =0; y < nodeCountY; y++){
Vector3 pos = new Vector3(
-mapWidth/2 + x*squareSize + squareSize/2,
0,
-mapHeight/2 + y*squareSize + squareSize/2);
controlNodes[x,y] = new ControlNode(pos, map[x,y]==1, squareSize);
}
}
squares = new Square[nodeCountX-1, nodeCountY-1];
for (int x = 0; x < nodeCountX-1; x++){
for(int y =0; y < nodeCountY-1; y++){
squares[x,y] = new Square(controlNodes[x,y+1],
controlNodes[x+1,y+1],
controlNodes[x+1,y],
controlNodes[x,y] );
}
}
}
}
public class Square{
public ControlNode topLeft, topRight, bottomLeft, bottomRight;
public Node midTop, midRight, midLeft, midBottom;
public int config;
public Square (ControlNode _topLeft, ControlNode _topRight, ControlNode _bottomRight, ControlNode _bottomLeft){
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
midTop = topLeft.right;
midRight = bottomRight.above;
midBottom = bottomLeft.right;
midLeft = bottomLeft.above;
if (topLeft.active)
config += 8;
if (topRight.active)
config += 4;
if(bottomRight.active)
config += 2;
if(bottomLeft.active)
config += 1;
}
}
public class Node {
public Vector3 position;
public int index = -1;
public Node(Vector3 _pos){
position = _pos;
}
}
public class ControlNode : Node{
public bool active; //active=wall
public Node above, right;
public ControlNode(Vector3 _pos, bool _active, float squareSize) : base(_pos){
active = _active;
above = new Node(position + Vector3.forward*squareSize/2f);
right = new Node(position + Vector3.right*squareSize/2f);
}
}
}
/*
if (newMesh==0){
//MeshCollider wallCollider = walls.gameObject.AddComponent<MeshCollider>();
wallCollider = walls.gameObject.AddComponent<MeshCollider>();
newMesh=1;
}
wallCollider.sharedMesh = mesh;
*/
/*
checkedList.Add(s.topLeft.index);
checkedList.Add(s.topRight.index);
checkedList.Add(s.bottomRight.index);
checkedList.Add(s.bottomLeft.index);
*/
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
[RequireComponent(typeof(Shadow))]
public class FlexibleUIText : FlexibleUI
{
Text txt;
public string Text;
public int size;
/*
* Attached text components
* and set the skin parameters
*/
protected override void OnSkinUI()
{
base.OnSkinUI();
txt = GetComponent<Text>();
//txt = GetComponent<Text>();
txt.font = skinData.m_font;
if (size > 0)
txt.fontSize = size;
else
txt.fontSize = skinData.m_fontsize;
txt.alignByGeometry = skinData.m_alignByText;
txt.alignment = skinData.m_Alignment;
txt.alignment = TextAnchor.MiddleCenter;
txt.text = Text;
txt.verticalOverflow = skinData.verticalOverflow;
txt.horizontalOverflow = skinData.horizontalOverflow;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
public class MapGenerator : MonoBehaviour {
int clearance = 5;
public string seed;
public bool useRandomSeed;
public int width;
public int height;
public int smoothFactor;
public int nFactor;
public int sz;
public int borderSize;
[Range(0,100)]
public int fillPercent;
System.Random randomGen;
//public NavMeshSurface floor;
Transform[] SpawnPoints;
public GameObject gm;
public GameObject treegroup;
int [,] map;
List<GameObject> trees = new List<GameObject>();
string[] treetypes = {};
string treelog;
string extra = "";
int midx;
int midy;
int [,] borderMap;
void Awake(){
Scene scene = SceneManager.GetActiveScene();
switch((int)scene.buildIndex){
case 1:
string[] obj = {"Tree_1", "Tree_2", "Tree_3"};
treelog = "Log_3";
treetypes = obj;
break;
case 3:
string[] obj3 = {"Mounting_1", "Mounting_2", "Mounting_3"};
treetypes = obj3;
treelog = "Flat_Rock_01";
extra = "Flat_Cactus_02";
//treelog = "Log_3";
break;
case 5:
string[] obj5 = {"SnowStone1", "SnowStone2", "SnowStone3"};
treetypes = obj5;
extra = "Pine_Snowy1";
treelog = "SnowStone10";
//treelog = "Log_3";
break;
}
SpawnPoints = gm.GetComponentInChildren<GameManager>().spawnPoints;
GenerateMap();
//floor.BuildNavMesh();
}
void Update(){
//regenerate with right mouse click
if (Input.GetMouseButtonDown(1)){
foreach(GameObject o in trees){
GameObject.Destroy(o.gameObject);
}
trees.Clear();
GenerateMap();
//floor.BuildNavMesh();
}
}
void GenerateMap(){
map = new int[width,height];
randomFillMap();
midx = width/2;
midy = height/2;
//clear space for the player at 0,0,0
for(int i = -clearance; i < clearance; i++){
for(int j = -clearance; j < clearance; j++){
map[i+midx,j+midy] = 0;
}
}
//clear space for the enemy spawn points
int spx, spy;// spz;
int path_margin = 2;
for(int k = 0; k < SpawnPoints.GetLength(0); k++){
spx = (int)SpawnPoints[k].position.x;
spy = (int)SpawnPoints[k].position.z; // z axis is y in this 2d coordinate
//spz = SpawnPoints[j].z;
//
for(int i = -clearance; i < clearance; i++){
for(int j = -clearance; j < clearance; j++){
map[spx+midx+i,spy+midy+j] = 0;
}
}
/*
GameObject sp = Instantiate(Resources.Load("Rock_1"),
new Vector3(spx, 0, spy), Quaternion.identity) as GameObject;
*/
//connect path enemy spawn points to the player
int flipx;
int flipy;
//int tempmid;
if (spx+midx < midx ) {flipx = 1;} else { flipx = -1;}
if (spy+midy < midy ) {flipy = 1;} else { flipy = -1;}
for (int j = spx+midx; j != midx; j += flipx){
for (int l = -path_margin; l < path_margin; l++){
map[j, spy+midy+l] = 0;
}
}
for (int j = spy+midy; j != midy; j += flipy){
for (int l = -path_margin; l < path_margin; l++){
map[midx+l, j] = 0;
}
}
}
for (int i = 0; i < smoothFactor; i++){
SmoothMap();
}
//add border to the map
borderMap = new int[width + borderSize*2, height +borderSize*2];
for(int x = 0; x < borderMap.GetLength(0); x++){
for(int y = 0; y < borderMap.GetLength(1); y++){
if(x>=borderSize && x < width && y >=borderSize && y < height){
borderMap[x,y] = map[x-borderSize,y-borderSize];
} else {
borderMap[x,y] = 1;
}
}
}
//setobj();
MeshGenerator meshGen = GetComponent<MeshGenerator>();
meshGen.GenerateMesh(borderMap, sz);
}
Vector3 returnHeight(Vector3 pos){
RaycastHit hit;
if (Physics.Raycast(pos+Vector3.up*10, Vector3.down, out hit,100f)){
//Debug.Log(hit.point);
return hit.point;
}
return pos;
}
public void setobj(){
// randomly set trees
int other=0;
float xloc;
float yloc;
for(int x = 0; x < borderMap.GetLength(0); x++){
for(int y = 0; y < borderMap.GetLength(1); y++){
xloc = (-width/2+x-borderSize)*sz + 0.5f;
yloc = (-height/2+y-borderSize)*sz + 0.5f;
if (borderMap[x,y] ==1){
other++;
if (other%17==0 && GetNeighborCount(x,y) >= 4){
GameObject myTreeInstance =
Instantiate(Resources.Load(
treetypes[randomGen.Next(0,3)]),
returnHeight(new Vector3(xloc, 2, yloc)),
Quaternion.identity) as GameObject;
trees.Add(myTreeInstance);
myTreeInstance.transform.SetParent(treegroup.transform);
} else if (other%2==0 && other%17!=0) {
//} if (GetNeighborCount(x,y) >= 3) {
GameObject terrainInst =
Instantiate(Resources.Load(treelog),
returnHeight(new Vector3(xloc, 2, yloc)),
Quaternion.identity) as GameObject;
trees.Add(terrainInst);
terrainInst.transform.SetParent(treegroup.transform);
}
else if (other%11==0 && extra!=""){
GameObject terrainInst =
Instantiate(Resources.Load(extra),
returnHeight(new Vector3(xloc, 2, yloc)),
Quaternion.identity) as GameObject;
trees.Add(terrainInst);
terrainInst.transform.SetParent(treegroup.transform);
}
}
}
}
}
void randomFillMap(){
if (useRandomSeed){
//seed = Time.time.ToString();
seed = DateTime.Now.Ticks.ToString();
}
//System.Random randomGen = new System.Random(seed.GetHashCode());
randomGen = new System.Random(seed.GetHashCode());
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
if (x==0 || x==width-1 || y==0 || y==height-1){
map[x,y] = 1; /* Mark all the edges as wall */
} else {
map[x,y] = (randomGen.Next(0,100) < fillPercent) ? 1 : 0;
}
}
}
}
void SmoothMap(){
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
int nCount = GetNeighborCount(x,y);
if (nCount > nFactor) {
map[x,y] = 1;
} else if ( nCount < nFactor){
map[x,y] = 0;
}
}
}
}
int GetNeighborCount(int xpos, int ypos){
int count = 0;
for (int nx = xpos-1; nx <= xpos+1; nx++){
for(int ny = ypos-1; ny <= ypos+1; ny++){
if (nx >= 0 && nx < width && ny >=0 && ny < height){
if (nx != xpos || ny != ypos){
count += map[nx,ny];
}
} else {
count++;
}
}
}
return count;
}
}
/*
private IEnumerator coroutine;
// every 2 seconds perform the print()
private IEnumerator WaitAndPrint(float waitTime)
{
while (true)
{
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}
*/
/*
print("Starting " + Time.time);
coroutine = WaitAndPrint(2.0f);
StartCoroutine(coroutine);
print("Before WaitAndPrint Finishes " + Time.time);
*/
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using com.heparo.terrain.toolkit;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
public class TerrainGenerator : MonoBehaviour {
public Texture2D cliffTexture;
public Texture2D sandTexture;
public Texture2D grassTexture;
public Texture2D rockTexture;// = (Texture2D)Resources.LoadAssetAtPath("Assets/com/heparo/terrain/toolkit/editor/resources/Dirt.jpg", typeof(Texture2D));
public Texture2D[] Textures;
public NavMeshSurface floor;
public GameObject mm;
//public GameObject nn;
float normalizeFactor;// = 0.02f;
//float[] slopeStops = new float[] { 20.0f, 50.0f };
//float[] heightStops = new float[] { .2f, .4f, .6f, .8f };
float[] slopeStops; //= new float[] { 30.0f, 45.0f };
float[] heightStops; //= new float[] { .025f, .05f, .06f, .07f };
Texture2D[] textures;
// Use this for initialization
void Start () {
GameManager ss = mm.GetComponent<GameManager>();
//MapGenerator tt = nn.GetComponent<MapGenerator>();
MapGenerator tt = transform.parent.GetComponent<MapGenerator>();
TerrainToolkit toolkit = GetComponent<TerrainToolkit>();
toolkit.resetTerrain();
Scene scene = SceneManager.GetActiveScene();
switch((int)scene.buildIndex){
case 1:
textures = new Texture2D[] { cliffTexture, sandTexture, grassTexture, rockTexture};
slopeStops = new float[] { 30.0f, 45.0f };
heightStops = new float[] { .025f, .05f, .06f, .07f };
normalizeFactor = 0.02f;
toolkit.VoronoiGenerator(com.heparo.terrain.toolkit.TerrainToolkit.FeatureType.Hills, 20, 1, 0.75f, 0.25f);
break;
case 3:
textures = new Texture2D[] {Textures[18], Textures[19], Textures[20], Textures[19]};
slopeStops = new float[] {30.025f, 30.05f};
heightStops = new float[] { .025f, .05f, .06f, .07f };
toolkit.VoronoiGenerator(com.heparo.terrain.toolkit.TerrainToolkit.FeatureType.Plateaus, 5, 1, 0.0f, 0.25f);
//toolkit.PerlinGenerator(2, 0.5f, 9, 1.0f);
normalizeFactor = 0.02f;
break;
case 5:
textures = new Texture2D[] {Textures[21], Textures[21], Textures[20], Textures[21]};
slopeStops = new float[] {30.025f, 30.05f};
heightStops = new float[] { .025f, .05f, .06f, .07f };
toolkit.VoronoiGenerator(com.heparo.terrain.toolkit.TerrainToolkit.FeatureType.Mountains, 5, 1, 0.0f, 0.25f);
//toolkit.PerlinGenerator(2, 0.5f, 9, 1.0f);
normalizeFactor = 0.04f;
break;
}
/*********
//PerlinGenerator(int frequency, float amplitude, int octaves, float blend)
*********/
//toolkit.PerlinGenerator(2, 0.5f, 9, 1.0f);
/********
VoronoiGenerator(FeatureType featureType, int cells, float features, float scale, float blend)
**********/
//TextureTerrain(float[] slopeStops, float[] heightStops, Texture2D[] textures)
toolkit.TextureTerrain(slopeStops, heightStops, textures);
//NormaliseTerrain(float minHeight, float maxHeight, float blend)
toolkit.NormaliseTerrain(0f, normalizeFactor, 1.0f);
floor.BuildNavMesh();
tt.setobj();
ss.beginGame();
}
// Update is called once per frame
void Update () {
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class changeMusic : MonoBehaviour {
public AudioClip level0Music;
public AudioClip level1Music;
public AudioClip level3Music;
public AudioClip level5Music;
public AudioClip IntroMusic;
public AudioClip oneToTwoMusic;
public AudioClip TwoToThreeMusic;
public AudioClip WinMusic;
private static AudioSource source;
private bool active;
/*
void Awake ()
{
source = GetComponent<AudioSource>();
}
*/
private static changeMusic instance;
public static changeMusic Instance
{
get { return instance; }
}
private void Awake()
{
// If no Player ever existed, we are it.
if (instance == null){
instance = this;
source = GetComponent<AudioSource>();
}
// If one already exist, it's because it came from another level.
else if (instance != this)
{
Destroy(gameObject);
return;
}
}
void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
public void toggleMusic(){
if (active){
source.Pause();
active = false;
}
else {
source.Play();
active = true;
}
}
/*
* Load music depending on the game level.
*/
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
switch((int)scene.buildIndex){
case 1:
source.clip = level1Music;
source.Play ();
break;
case 2:
source.clip = WinMusic;
source.Play ();
break;
case 3:
source.clip = level3Music;
source.Play ();
break;
case 4:
source.clip = IntroMusic;
source.Play ();
break;
case 5:
source.clip = level5Music;
source.Play ();
break;
case 6:
source.clip = oneToTwoMusic;
source.Play ();
break;
case 7:
source.clip = TwoToThreeMusic;
source.Play ();
break;
default:
source.clip = level0Music;
source.Play ();
break;
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class WaveManager : MonoBehaviour
{
public GameObject enemy;
public List<GameObject> enemies = new List<GameObject>(); //create list of enemies to spawn for each wave
public float spawnTime = 3f;
public Transform[] spawnPoints;
public int currentLevel; // The current level.
public int currentWave; // The current wave.
public static int foesLeft; // Foes Left to defeat before wave ends.
public Text infoText; // Reference to the Text component for level, wave, foes left.
public Text waveClearText; // Reference to the Text component for wave cleared text.
public static int[] waves = new int[] {0, 5, 45, 80};
public int finalWave = waves.Length - 1;
float timeRemaining = 10;
void Awake ()
{
infoText = GetComponentInChildren <Text> ();
waveClearText.text = ""; //testing now.
//when game starts, start on level 1 wave 1, create list of enemy game objects
SetLevel(1);
SetWave(1);
CreateEnemyList();
Spawn ();
}
void Update ()
{
if (foesLeft == 0) {
//waveClearText.text = "Wave Cleared!";
if (timeRemaining >= 0) {
timeRemaining -= Time.deltaTime;
waveClearText.text = "Wave Cleared! New Waves Spawning In: " + timeRemaining.ToString ("f0");
print (timeRemaining);
}
}
//CheckFoesLeft();
infoText.text = "Level: " + currentLevel + "\nWave: " + currentWave + "\nFoes: " + foesLeft;
}
//init list of enemy objects for spawn on each wave
void CreateEnemyList() {
enemies.Clear();
for (int i = 0; i < foesLeft; i++) {
//Debug.Log(i);
enemies.Add(enemy);
}
}
void SetLevel(int level) {
currentLevel = level;
}
void SetWave(int wave) {
currentWave = wave;
foesLeft = waves[currentWave];
}
void Spawn()
{
int spawnPointIndex;
for (int i = 0; i < foesLeft; i++) {
spawnPointIndex = Random.Range(0, spawnPoints.Length);
//this is a Transform, each Transform has a position and rotation
Instantiate (enemies[i], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
//Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed = 7f;
Vector3 movement;
Animator anim;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
public Camera firstPerson;
public Camera thirdPerson;
// Use this for initialization
void Awake () {
floorMask = LayerMask.GetMask ("Floor");
anim = GetComponent <Animator> ();
playerRigidbody = GetComponent<Rigidbody> ();
transform.Translate(Vector3.up*10);
RaycastHit hit;
if(Physics.Raycast(transform.position, Vector3.down, out hit, 100f)){
//Debug.Log(hit.point);
transform.position = hit.point;
//transform.Translate(hit.point);
//transform.Translate(Vector3.down*(10-hit.point.y));
}
}
// Update is called once per frame
void FixedUpdate () {
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
// Move the player around the scene.
if(thirdPerson.gameObject.activeSelf) {
// Turn the player to face the mouse cursor.
Move (h, v);
Turning ();
}
else { //first person control different
h *= speed;
v *= speed;
h *= Time.deltaTime;
v *= Time.deltaTime;
transform.Translate(h, 0, v);
}
Animating (h, v);
}
public void changeMovementSpeed(float s) {
speed = s;
}
void Move(float h, float v) {
movement.Set (h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning() {
// Create a ray from the mouse cursor on screen in the direction of the camera.
Ray camRay = thirdPerson.ScreenPointToRay (Input.mousePosition);
// Create a RaycastHit variable to store information about what was hit by the ray.
RaycastHit floorHit;
// Perform the raycast and if it hits something on the floor layer...
if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
{
// Create a vector from the player to the point on the floor the raycast from the mouse hit.
Vector3 playerToMouse = floorHit.point - transform.position;
// Ensure the vector is entirely along the floor plane.
playerToMouse.y = 0f;
// Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
// Set the player's rotation to this new rotation.
playerRigidbody.MoveRotation (newRotation);
}
}
void Animating(float h, float v) {
// Create a boolean that is true if either of the input axes is non-zero.
bool walking = h != 0f || v != 0f;
// Tell the animator whether or not the player is walking.
anim.SetBool ("IsWalking", walking);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class loadScene : MonoBehaviour {
public int level;
public Button startButton;
public GameObject loadingImage;
//public Slider loadingBar;
//private AsyncOperation async;
void Awake()
{
startButton.onClick.AddListener(
delegate() {LoadByIndex();}
);
}
void LoadByIndex()
{
StartCoroutine(LoadYourAsyncScene());
}
IEnumerator LoadYourAsyncScene()
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(level);
asyncLoad.allowSceneActivation = false;
loadingImage.SetActive(true);
//SceneManager.LoadScene (index);
//Wait until the last operation fully loads to return anything
while (asyncLoad.progress < 0.9f)
//while (!asyncLoad.isDone)
{
//loadingBar.value = asyncLoad.progress;
yield return null;
}
asyncLoad.allowSceneActivation = true;
}
}
| c23e3108d291ad6863fea6d01fde66e67942ddc8 | [
"Markdown",
"C#"
] | 16 | C# | sl424/Unity-ProcederalEnvironment | 998f749ce81ef5268801c3052cfeef9c55a0942c | e332c8b6cd6939207a82cb58e4ad0eac19dcc847 |
refs/heads/master | <repo_name>jcalvomendoza/suavibot<file_sep>/messages/index.js
/*-----------------------------------------------------------------------------
This template demonstrates how to use an IntentDialog with a LuisRecognizer to add
natural language support to a bot.
For a complete walkthrough of creating this type of bot see the article at
https://aka.ms/abs-node-luis
-----------------------------------------------------------------------------*/
"use strict";
var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
var path = require('path');
var useEmulator = (process.env.NODE_ENV == 'development');
var connector = useEmulator ? new builder.ChatConnector() : new botbuilder_azure.BotServiceConnector({
appId: process.env['MicrosoftAppId'],
appPassword: <PASSWORD>['<PASSWORD>App<PASSWORD>'],
openIdMetadata: process.env['BotOpenIdMetadata']
});
/*----------------------------------------------------------------------------------------
* Bot Storage: This is a great spot to register the private state storage for your bot.
* We provide adapters for Azure Table, CosmosDb, SQL Azure, or you can implement your own!
* For samples and documentation, see: https://github.com/Microsoft/BotBuilder-Azure
* ---------------------------------------------------------------------------------------- */
var tableName = 'botdata';
var azureTableClient = new botbuilder_azure.AzureTableClient(tableName, process.env['AzureWebJobsStorage']);
var tableStorage = new botbuilder_azure.AzureBotStorage({ gzipData: false }, azureTableClient);
var bot = new builder.UniversalBot(connector);
bot.localePath(path.join(__dirname, './locale'));
bot.set('storage', tableStorage);
// Make sure you add code to validate these fields
var luisAppId = process.env.LuisAppId;
var luisAPIKey = process.env.LuisAPIKey;
var luisAPIHostName = process.env.LuisAPIHostName || 'westus.api.cognitive.microsoft.com';
const LuisModelUrl = 'https://' + luisAPIHostName + '/luis/v1/application?id=' + luisAppId + '&subscription-key=' + luisAPIKey;
// Main dialog with LUIS
var recognizer = new builder.LuisRecognizer(LuisModelUrl);
var intents = new builder.IntentDialog({ recognizers: [recognizer] })
.matches('askAboutMe', (session) => {
session.send('I\'m JaviBot');
session.sendTyping();
setTimeout(function(){
session.send('In the universe that is Javier, I\'m the night sky visible to the naked eye for those willing to look up.');
}, 3000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('But for all intents and purposes I\'m Javier.');
}, 4000);
setTimeout(function(){
session.sendTyping();
}, 4001);
setTimeout(function(){
session.send('I can tell you about my work experience, education, upbringing, hobbies, passions, and the like.');
}, 7000);
setTimeout(function(){
session.send(String.fromCharCode(0xD83D, 0xDE01));
}, 8000);
})
.matches('askAboutFeeling', (session) => {
session.send('I\'m well!');
session.sendTyping();
setTimeout(function(){
session.send('Excited to be talking to you.');
}, 3000);
})
.matches('askAge', (session) => {
session.send('I\'m 28 years old.');
session.sendTyping();
setTimeout(function(){
session.send('I feel younger at heart, but definitely older on weekends though.');
}, 5000);
})
.matches('askBackground', (session) => {
session.send('I was born in Madrid, Spain, grew up in San Salvador, El Salvador, and now live in Chicago, IL.');
})
.matches('askAboutSpain', (session) => {
session.send('I was just 3 years old when I left Spain, so there is not much I remember');
session.send('I\'ve returned many times since, though, and I have found that in many ways, the feelings created by the memories I make now, fill in for those I missed out on.');
})
.matches('askAboutEducation', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I got my bachelor\'s degree in Political Science & Economics from Colgate University.');
}, 3000);
setTimeout(function(){
session.send('I graduated <NAME> and <NAME>.');
}, 4000);
setTimeout(function(){
session.sendTyping();
}, 4001);
setTimeout(function(){
session.send('I\'m currently pursuing my MBA at the University of Chicago\'s Booth School of Business.');
}, 6000);
setTimeout(function(){
session.sendTyping();
}, 6001);
setTimeout(function(){
session.send('Concentrating in Marketing, Satistics, and Finance.');
}, 7000);
setTimeout(function(){
session.send('I\'ll be done in late 2018.');
}, 8000);
})
.matches('askAboutWork', (session) => {
session.send('I\'ve been a Product Manager at McMaster-Carr Supply Co. for 4 years now.');
session.send('I\'ve managed ordering ecosystems, customers\' delivery experience, as well as internal applications');
})
.matches('askAboutOrdering', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I\'ve been the Ordering Product Manager for the better part of a year now.');
}, 1000);
setTimeout(function(){
session.sendTyping();
}, 1001);
setTimeout(function(){
session.send('In that time, we\'ve streamlined the ordering experience and integrated it with the entire order lifecycle.');
}, 4000);
setTimeout(function(){
session.sendTyping();
}, 4001);
setTimeout(function(){
session.send('We brought powerful search functionality that makes it easy for users to search by order number, invoice number, part number, item category . . . the whole 9 yards.');
}, 9000);
setTimeout(function(){
session.sendTyping();
}, 9001);
setTimeout(function(){
session.send('We added a single click re-order option for single items or entire orders.');
}, 10000);
setTimeout(function(){
session.sendTyping();
}, 10001);
setTimeout(function(){
session.send('Then we integrated the cart into users\' order history, allowing them to easily build new orders and keep track of the progress of the order.');
}, 15000);
setTimeout(function(){
session.sendTyping();
}, 15001);
setTimeout(function(){
session.send('We also designed saved orders to be flexible, easy to place, but also function as collections.');
}, 17000);
setTimeout(function(){
session.sendTyping();
}, 17001);
setTimeout(function(){
session.send('By abstracting a plethora of user needs into a few basic functional models, we designed a very flexible ordering ecosystem that served many idiosyncratic needs and whose design was not inherently prescriptive.');
}, 22000);
setTimeout(function(){
session.sendTyping();
}, 22001);
setTimeout(function(){
session.send('Really, cool stuff, in my opinion.');
}, 23000);
setTimeout(function(){
session.sendTyping();
}, 23001);
setTimeout(function(){
session.send('Also related to Ordering was my work on Order History.');
}, 25000);
})
.matches('askAboutOrderHistory', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('Several years ago, we re-designed the Order History page');
}, 3000);
setTimeout(function(){
session.send('I managed the launch of the feature.');
}, 4000);
setTimeout(function(){
session.sendTyping();
}, 4001);
setTimeout(function(){
session.send('But more rewarding, however, was working to develop very powerful search features within Order History, particularly searching by product family, name, or number.');
}, 7000);
setTimeout(function(){
session.sendTyping();
}, 7001);
setTimeout(function(){
session.send('As much as we like to think of our business as a non-repeat purchase one, the truth is our customers operate expensive hardware with durable lives of decades. Ordering the same or similar parts over and over is extremely common.');
}, 12000);
setTimeout(function(){
session.sendTyping();
}, 12001);
setTimeout(function(){
session.send('This work was a fabulous stepping stone to some of my later work supporting complex ordering flows. Imagine being able to type \'hex nut\' and finding that one nut you ordered 5 years ago and adding it to your cart with a single click.');
}, 17000);
})
.matches('askAboutOrderContinuity', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('For the longest time, we didn\'t require a login for users to place orders. We used cookie values to persist the cart over time.');
}, 3000);
setTimeout(function(){
session.send('So carts were tied to a browser, not a login.');
}, 4000);
setTimeout(function(){
session.sendTyping();
}, 4001);
setTimeout(function(){
session.send('But as customers begin to interact with us through multiple devices, that construct has become antiquated.');
}, 6000);
setTimeout(function(){
session.sendTyping();
}, 6001);
setTimeout(function(){
session.sendTyping();
}, 9001);
setTimeout(function(){
session.send('The problem is that our biggest (and most bureaucratic) customers have incorporated this construct into their workflows as a way to circumvent the fact that we do not support company-wide logins or accounts per se.');
}, 12000);
setTimeout(function(){
session.sendTyping();
}, 12001);
setTimeout(function(){
session.send('And it is hard to differentiate these users from those who share a login to build a common cart, in both cases we observe a single login, multiple orders, and multiple devices.');
}, 15000);
setTimeout(function(){
session.sendTyping();
}, 15001);
setTimeout(function(){
session.send('I wanted to preserve the experience from an important and vocal miniroty without depriving the majority of our customers from an experience that is standard and expected today.');
}, 18000);
})
.matches('askAboutDelivery', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I was the Delivery Experience Product Manager for almost 2 years.');
}, 3000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('One of our big deliverables was, well . . . delivery estimates on our site.');
}, 5000);
setTimeout(function(){
session.sendTyping();
}, 5001);
setTimeout(function(){
session.send('Sounds really basic, but it\'s not really when you have a complex delivery network aimed at achieving next-day delivery, but rife with exceptions for hazards and other items regulated for transport.');
}, 8000);
setTimeout(function(){
session.sendTyping();
}, 8001);
setTimeout(function(){
session.send('But what I\'m really proud of is helping create a score-based algorithm that will consider days to delivery, delivery time, delivery cost to the company and the customer, number of packages and more to make the best shipping decision.' );
}, 12000);
setTimeout(function(){
session.sendTyping();
}, 12001);
setTimeout(function(){
session.send('Most parameters are set to replicate today\'s outcomes - but our model is flexible enough to adapt to changes overnight, say a rate hike by UPS but not FedEx. But, even cooler, to eventually consider factors such as real-time fulfillment center work-in-process, to determine the best fulfillment center to fill from and shipping method.' );
}, 18000);
setTimeout(function(){
session.sendTyping();
}, 18001);
setTimeout(function(){
session.send('It\'s hard to ever look at e-commerce the same way now.' );
}, 20000);
})
.matches('askAboutInternalApplications', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('Managing software that automated the entry of e-mail orders into our order processing system was my first product management role.');
}, 5000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('I came in halfway and my goal was not to get the software built but rather to improve on it.');
}, 7000);
setTimeout(function(){
session.sendTyping();
}, 7001);
setTimeout(function(){
session.send('At the time 11% of orders e-mailed were processed by our system without the need of a human touch. By the time I left, the number was 30%');
}, 9000);
setTimeout(function(){
session.sendTyping();
}, 9001);
setTimeout(function(){
session.send('I loved this project because it required careful analysis of document and e-mail patterns and because we had to critically juggle tradeoffs throughout - if we loosen or change this constraint in the software\'s business logic, how many instances do we improve and how many do we make worse as a result.' );
}, 13000);
})
.matches('askAboutHobbies', (session) => {
session.send('I have more hobbies than I have time for.');
setTimeout(function(){
session.sendTyping();
}, 1000);
setTimeout(function(){
session.send('I love hockey. I like to run. I try to keep my French, German, and Italian up to snuff, I\'m a film fanatic, I dabble in photography, and try to regularly visit the Chicago Cultural Center as well as the Art Institute.');
}, 5000);
})
.matches('askAboutLanguages', (session) => {
setTimeout(function(){
session.sendTyping();
}, 1);
setTimeout(function(){
session.send('Spanish is my first language and I\'m fluent in English, though I might have already given that away.');
}, 3000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('I\'m fluent in French and conversational in German and Italian.');
}, 6000);
})
.matches('askAboutHockey', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I did not see snow until I was 19, so naturally, hockey was a perfect fit. My 5\'6\'\' stature was also a plus.');
}, 3000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('That\'s why I think I love hockey so much though. Because I never saw myself playing it, because I thought I was too old to ever pick up a stick.');
}, 6000);
setTimeout(function(){
session.sendTyping();
}, 6001);
setTimeout(function(){
session.send('Yet, here I am, and so is my tailbone. Doing the new and unexpected is so rewarding.');
}, 6000);
})
.matches('askAboutFilm', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('Like other media, I love how films can memorialize a feeling. They can be played and re-played and with them memories lived and re-lived, and feelings felt and felt again.');
}, 5000);
setTimeout(function(){
session.sendTyping();
}, 5001);
setTimeout(function(){
session.send('That\'s why my favorite films are slow and uneventful, but captivating in the beauty with which they capture the wonders of daily life. It\'s one indirect path to develop empathy.');
}, 10000);
setTimeout(function(){
session.sendTyping();
}, 10001);
setTimeout(function(){
session.send('Before the reality that my parents could not support me beyond my collegiate ambitions, I always wanted to be an actor.');
}, 15000);
setTimeout(function(){
session.sendTyping();
}, 15001);
setTimeout(function(){
session.send('It felt like the most direct path between me and the feelings of others.');
}, 17000);
setTimeout(function(){
session.sendTyping();
}, 17001);
setTimeout(function(){
session.send('I reach people through products and experiences, today - the path is not as direct, but it can be as rewarding.');
}, 1900);
})
.matches('askAboutSkills', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I\'m well-versed in the entire Microsoft Office suite, but these days, that\'s like saying I know how to use a cellphone.');
}, 5000);
setTimeout(function(){
session.sendTyping();
}, 5001);
setTimeout(function(){
session.send('I also use most programs from the Adobe Suite regularly.');
}, 8000);
setTimeout(function(){
session.sendTyping();
}, 8001);
setTimeout(function(){
session.send('I use Adobe Illustrator the most, but also rely heavily on InDesign, After Effects, and Captivate.');
}, 11000);
setTimeout(function(){
session.sendTyping();
}, 11001);
setTimeout(function(){
session.send('I use Neo4J graph databases and the Cypher Query Language daily, and SQL on occasion.');
}, 15000);
setTimeout(function(){
session.sendTyping();
}, 15001);
setTimeout(function(){
session.send('I do data analysis with R.');
}, 17000);
setTimeout(function(){
session.sendTyping();
}, 17001);
setTimeout(function(){
session.send('And outside of work, I use Sketch and Framer to prototype interactive designs and Javascript to create this site or this bot.');
}, 20000);
setTimeout(function(){
session.sendTyping();
}, 20001);
setTimeout(function(){
session.send('You can ask me to elaborate on any of these, if you\'d like.');
}, 23000);
})
.matches('askAboutGraphDatabase', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('I use Neo4j and CQL to inform and iterate on the design of the products and features I manage.');
}, 3000);
setTimeout(function(){
session.sendTyping();
}, 3001);
setTimeout(function(){
session.send('For example, what was the marginal effect of an additional day of lead time on conversion rates for any given part number, when I worked on bringing transparent lead times, based on supplier information to our site.');
}, 9000);
setTimeout(function(){
session.sendTyping();
}, 9001);
setTimeout(function(){
session.sendTyping();
}, 12001);
setTimeout(function(){
session.send('Or differentiating between users who share logins in order to have a common cart from users who share a login to have a common order history, but build orders separately, based on interaction patterns originating from different devices tied to the users\' login.');
}, 16000);
setTimeout(function(){
session.sendTyping();
}, 16001);
setTimeout(function(){
session.send('Why that distinction was even important, is a bit of an aside, and was tied to a change to push the active cart to all devices where the user was logged in, something we called \'Order Continuity.\'');
}, 20000);
setTimeout(function(){
session.sendTyping();
}, 20001);
setTimeout(function(){
session.send('And why our site didn\'t already work like that, is also a bit tangential, but you can ask me about it if you\'re curious.');
}, 22000);
})
.matches('askAboutPrototyping', (session) => {
session.sendTyping();
setTimeout(function(){
session.send('Sorry, I\'m still learning how to respond to that. The real Javier can answer it though!');
}, 3000);
})
.matches('Help', (session) => {
session.send('I can tell you about my work experience, education, upbringing, hobbies, passions, and the like.');
session.sendTyping();
setTimeout(function(){
session.send('Alternatively you can click on the contact link on the top right and reach me through any number of media.');
}, 3000);
})
.matches('Cancel', (session) => {
session.send('You reached Cancel intent, you said \'%s\'.', session.message.text);
})
/*
.matches('<yourIntent>')... See details at http://docs.botframework.com/builder/node/guides/understanding-natural-language/
*/
.onDefault((session) => {
session.send('\'%s\'? I\'m not sure what to do with that. Why don\'t you e-mail the real Javier at <EMAIL> ', session.message.text);
});
bot.dialog('/', intents);
if (useEmulator) {
var restify = require('restify');
var server = restify.createServer();
server.listen(3978, function() {
console.log('test bot endpont at http://localhost:3978/api/messages');
});
server.post('/api/messages', connector.listen());
} else {
module.exports = connector.listen();
}
| afe78c4cbc3fa53978d572f12c238c0307b8a21e | [
"JavaScript"
] | 1 | JavaScript | jcalvomendoza/suavibot | 84b01506359189ef3b0bddd77c67b7af065d6dcd | f86355a8e7a3787572d61514832085b9adcd0d42 |
refs/heads/main | <repo_name>aadesh0928/DesignPatternConsole<file_sep>/ConsoleApp1/BookRepository.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class BookRepository
{
public IEnumerable<Book> GetBooks()
{
return new List<Book>()
{
new Book() {Title = "C#", Price = 23.8f },
new Book() {Title = "ASP.Net Step by Step", Price = 223.8f },
new Book() {Title = ".Net core web api", Price = 73.8f },
new Book() {Title = "C# Advanced", Price = 233.8f }
};
}
}
public class Book
{
public string Title { get; set; }
public double Price { get; set; }
}
}
<file_sep>/ConsoleApp1/AdapterPattern.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp11
{
public class Client
{
private readonly ITarget _employees;
public Client(ITarget employees)
{
_employees = employees;
}
public void DisplayEmployees()
{
foreach(var emp in _employees.GetEmployees())
{
Console.WriteLine($"Name of employee is {emp}");
}
}
}
public interface ITarget
{
List<string> GetEmployees();
}
public class EmployeeAdapter : SAP, ITarget
{
public List<string> GetEmployees()
{
return FetchEmployees();
}
}
public class SAP
{
public List<string> FetchEmployees()
{
return new List<string> { "aadesh", "tom", "harry" };
}
}
public class AdapterPattern
{
public static void Main2(string[] args)
{
//var l = new List<string> { "A", "B", "C" };
//var r = Enumerable.Reverse(l);
ITarget employeeTarget = new EmployeeAdapter();
var clientEmployeeApp = new Client(employeeTarget);
clientEmployeeApp.DisplayEmployees();
}
}
}
<file_sep>/ConsoleApp1/DecoratorPattern.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
public abstract class Order
{
protected List<Product> products = new List<Product>
{
new Product { Name = "ABC", Price = 23.34f },
new Product { Name = "ABC", Price = 23.34f },
new Product { Name = "ABC", Price = 23.34f },
new Product { Name = "ABC", Price = 23.34f }
};
public abstract double CalculateOrderTotal();
}
class NormalOrder: Order
{
public override double CalculateOrderTotal()
{
Console.WriteLine("Calculating the total price of a regular order");
return products.Sum(product => product.Price);
}
}
class DiscountedOrder : Order
{
private double _discount { get; set; }
public DiscountedOrder(double discount)
{
_discount = discount;
}
public override double CalculateOrderTotal()
{
Console.WriteLine("Calculating the total price of a regular order");
return products.Sum(product => product.Price) * _discount;
}
}
public class OrderDecorator : Order
{
protected Order _order;
public OrderDecorator(Order order)
{
_order = order;
}
public override double CalculateOrderTotal()
{
Console.WriteLine("Calculating the total price as per advance discouting logic");
return _order.CalculateOrderTotal();
}
}
public class PremiumOrder: OrderDecorator
{
private double _premiumDisCount;
public PremiumOrder(Order order, double premiumDiscoumt): base (order)
{
_premiumDisCount = premiumDiscoumt;
}
public override double CalculateOrderTotal()
{
var discountedProce = base.CalculateOrderTotal();
return discountedProce * _premiumDisCount;
}
}
class DecoratorPattern
{
public static void Main199898989(string[] args)
{
var discountedOrder = new DiscountedOrder(.9);
var premiumOrder = new PremiumOrder(discountedOrder, .11);
}
}
}
<file_sep>/ConsoleApp1/CommandPattern.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp112
{
public class Product
{
public double Price { get; set; }
public string Name { get; set; }
public Product(string name, double price)
{
Name = name;
Price = price;
}
public void IncreasePrice(double amount)
{
this.Price += amount;
Console.WriteLine($"The price of {Name} is increased by: {amount}");
}
public void DecreasePrice(double amount)
{
if(amount < Price)
{
Price -= amount;
Console.WriteLine($"The price of {Name} is decreased by: {amount}");
}
}
public override string ToString()
{
return $"The current price of the {Name} is {Price}";
}
}
public interface ICommand
{
void Execute();
}
public enum PriceAction
{
Increase,
Decrease
}
public class ProductCommand: ICommand
{
private readonly Product _product;
private readonly PriceAction _priceAction;
private readonly double _amount;
public ProductCommand(Product product, PriceAction priceAction, double amount)
{
_product = product;
_priceAction = priceAction;
_amount = amount;
}
public void Execute()
{
if(_priceAction == PriceAction.Increase)
{
_product.IncreasePrice(_amount);
}
else
{
_product.DecreasePrice(_amount);
}
}
}
public class ModifyPrice
{
private readonly IList<ICommand> _commands;
private ICommand _command;
public ModifyPrice()
{
_commands = new List<ICommand>();
}
public void SetCommand(ICommand command) => _command = command;
public void Invoke()
{
_commands.Add(_command);
_command.Execute();
}
}
public class CommandPattern
{
public static void Main12(String[] args)
{
var modifyPrice = new ModifyPrice();
var product = new Product("Microsoft Windows 10", 2500.90f);
Execute(modifyPrice, new ProductCommand(product, PriceAction.Increase, 23.90f));
Execute(modifyPrice, new ProductCommand(product, PriceAction.Increase, 13.90f));
Execute(modifyPrice, new ProductCommand(product, PriceAction.Increase, 3.90f));
Console.WriteLine(product);
Console.ReadKey();
}
private static void Execute(ModifyPrice modifyPrice, ICommand command)
{
modifyPrice.SetCommand(command);
modifyPrice.Invoke();
}
}
}
<file_sep>/ConsoleApp1/Liskov.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class Liskov
{
public static void Main222(string[] args)
{
}
}
}
<file_sep>/ConsoleApp1/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp11111
{
class Program
{
public enum Color
{
Blue,
Green,
Red
}
public enum Size
{
Large,
Huge,
Small
}
public class Product
{
public string Name { get; set; }
public Size Size { get; set; }
public Color Color { get; set; }
public Product(string name, Color color, Size size)
{
if(name == null)
{
throw new ArgumentNullException(paramName: nameof(name));
}
Name = name;
Size = Size;
Color = color;
}
}
public class ProductFilter
{
public IEnumerable<Product> FilterBySize(IEnumerable<Product> products, Size size)
{
foreach(var p in products)
{
if(p.Size == size)
{
yield return p;
}
}
}
public IEnumerable<Product> FilterByColor(IEnumerable<Product> products, Color color)
{
foreach (var p in products)
{
if (p.Color == color)
{
yield return p;
}
}
}
public IEnumerable<Product> FilterBySizeAndColor(IEnumerable<Product> products, Color color, Size size)
{
foreach (var p in products)
{
if (p.Color == color && p.Size == size)
{
yield return p;
}
}
}
}
public abstract class A
{
private string _name;
private int? _age;
public A()
{
_name = "Aadesh";
_age = 34;
}
public int MAX_CHANCES()
{
return 100;
}
public abstract void F();
}
public class B : A
{
public B()
{
}
public new int[] MAX_CHANCES()
{
return new int[] { };
}
public override void F()
{
//
}
public void DF() { }
}
public class Person
{
public string Name { get; set; }
public string Position { get; set; }
public class Builder: PersonJobBuilder<Builder>
{
}
public static Builder BuilderInstance => new Builder();
public override string ToString()
{
return $"{nameof(Name)} : {Name}, {nameof(Position)} : {Position}";
}
}
public abstract class PersonBuilder
{
protected Person person = new Person();
public Person Build()
{
return person;
}
}
public class PersonInfoBuilder<T>: PersonBuilder
where T : PersonInfoBuilder<T>
{
public T Called(string name)
{
person.Name = name;
return this as T;
}
}
public class PersonJobBuilder<T>: PersonInfoBuilder<PersonJobBuilder<T>>
where T: PersonJobBuilder<T>
{
public T WorksAs(string position)
{
person.Position = position;
return this as T;
}
}
public interface IEmployee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Trainee<T> where T: Trainee<T>
{
public int Id { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public T GetTeainneInfo()
{
return this as T;
}
}
public class SuperVisor<T> : Trainee<SuperVisor<T>> where T: SuperVisor<T>
{
public T GetSuperVisorInfo()
{
return this as T;
}
}
public class Abc
{
public string name;
}
class XYZ
{
public Abc ComplexName { get; set; }
}
static void Main(string[] args)
{
Abc obj = null;
XYZ c = new XYZ();
c.ComplexName = new Abc();
c.ComplexName.name = "";
string tempName = null;
var result = c.ComplexName?.name?? tempName ?? string.Empty;
//var obj = new SuperVisor();
//obj.GetTeainneInfo().
// A aObj = new B();
//Console.WriteLine("Hidden Max_chances " + aObj.MAX_CHANCES());
//B bObj = new B();
//Console.WriteLine("New Impl. Max_chances " + bObj.MAX_CHANCES()
// .DefaultIfEmpty(999).Aggregate((acc, item)=> acc + item));
Console.WriteLine(Person.BuilderInstance.Called("aadesh").WorksAs("Staff Engineer").Build().ToString());
Console.ReadLine();
}
}
}
<file_sep>/ConsoleApp1/FacetedBuilderPattern.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public enum CarBodyType
{
MiniHatchback,
Hatchback,
SUV,
Sedan,
MiniSedan
}
public class Car
{
public CarBodyType CarType { get; set; }
public string Color { get; set; }
public int NoOfDoors { get; set; }
public string Address { get; set; }
public string City { get; set; }
public override string ToString()
{
return $"{nameof(CarType)} :" +
$" { CarType}, {nameof(Color)} : " +
$"{Color}, {nameof(NoOfDoors)}: " +
$"{NoOfDoors}, {nameof(Address)}: {Address}";
}
}
public class CarBuilder
{
public Car Car { get; set; }
public CarBuilder()
{
Car = new Car();
}
public Car Build() => Car;
public CarInfoBuilder Info => new CarInfoBuilder(Car);
public CarAddressBuilder Built => new CarAddressBuilder(Car);
}
public class CarInfoBuilder: CarBuilder
{
public CarInfoBuilder(Car car)
{
Car = car;
}
public CarInfoBuilder WithType(CarBodyType type)
{
Car.CarType = type;
return this;
}
public CarInfoBuilder WithColor(string color)
{
Car.Color = color;
return this;
}
public CarInfoBuilder WithNoOfDoors(int numDoors)
{
Car.NoOfDoors = numDoors;
return this;
}
}
public class CarAddressBuilder: CarBuilder
{
public CarAddressBuilder(Car car)
{
Car = car;
}
public CarAddressBuilder InCity(string city)
{
Car.City = city;
return this;
}
public CarAddressBuilder AtAddress(string address)
{
Car.Address = address;
return this;
}
}
public class Example
{
public static void Main1(string[] args)
{
var car = new CarBuilder().Info
.WithType(CarBodyType.SUV)
.WithColor("red")
.WithNoOfDoors(5)
.Built.InCity("Delhi").AtAddress("Rohini")
.Build();
Console.WriteLine(car);
Console.ReadLine();
}
}
}
<file_sep>/ConsoleApp1/OpenClose.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp122
{
public enum Color
{
Red,
Blue,
Green
}
public enum Size
{
Large,
Medium,
Small,
ExtraSmall,
ExtraLarge
}
public enum Brand
{
Reebook,
AmazonBasics,
Versace,
Puma
}
public class Product
{
private readonly string _name;
private readonly Color _color;
private readonly Size _size;
private readonly Brand _brand;
public Product(string name, Color color, Size size, Brand brand)
{
this._name = name;
this._color = color;
this._size = size;
_brand = brand;
}
public Color Color
{
get
{
return _color;
}
}
public string Name
{
get
{
return _name;
}
}
public Size Size
{
get
{
return _size;
}
}
public Brand Brand
{
get
{
return _brand;
}
}
public override string ToString()
{
return $"Product name : {Name}, Color: {Color}, Size: {Size}, Brand: {Brand}";
}
}
public interface ICriteria<T>
{
bool IsSatisfy(T item);
}
public interface IFilter<T> where T: class
{
IEnumerable<T> Filter(IEnumerable<T> items, ICriteria<T> criteria);
}
public class ColorFilterCriteria : ICriteria<Product>
{
private Color _color;
public ColorFilterCriteria(Color color)
{
_color = color;
}
public bool IsSatisfy(Product item)
{
return item.Color == _color;
}
}
public class SizeFilterCriteria : ICriteria<Product>
{
private Size _size;
public SizeFilterCriteria(Size size)
{
_size = size;
}
public bool IsSatisfy(Product item)
{
return item.Size == _size;
}
}
public class BrandFilterCriteria : ICriteria<Product>
{
private Brand _brand;
public BrandFilterCriteria(Brand brand)
{
_brand = brand;
}
public bool IsSatisfy(Product item)
{
return item.Brand == _brand;
}
}
public class AndCriteria<T> : ICriteria<T>
{
private ICriteria<T>[] _criterias;
public AndCriteria(params ICriteria<T>[] criteris)
{
_criterias = criteris;
}
public bool IsSatisfy(T item)
{
var isSatisfy = true;
foreach(var criteria in _criterias)
{
if(!criteria.IsSatisfy(item))
{
isSatisfy = false;
break;
}
}
return isSatisfy;
}
}
public class ProductFilter : IFilter<Product>
{
public IEnumerable<Product> Filter(IEnumerable<Product> items, ICriteria<Product> criteria)
{
return items.Where(item => criteria.IsSatisfy(item));
}
}
public class OpenClose
{
public static void Main1111(string[] args)
{
List<Product> products = new List<Product>()
{
new Product("T-Shirt", Color.Blue, Size.Medium, Brand.AmazonBasics),
new Product("T-Shirt", Color.Blue, Size.Small, Brand.Reebook),
new Product("T-Shirt", Color.Red, Size.Large, Brand.Puma),
new Product("T-Shirt", Color.Red, Size.Small, Brand.Puma),
new Product("T-Shirt", Color.Green, Size.Small, Brand.AmazonBasics),
new Product("T-Shirt", Color.Green, Size.ExtraSmall, Brand.Versace),
new Product("T-Shirt", Color.Blue, Size.ExtraLarge, Brand.AmazonBasics),
};
var productFilter = new ProductFilter();
foreach(var product in productFilter.Filter(products,
new AndCriteria<Product>(new ColorFilterCriteria(Color.Green),
new SizeFilterCriteria(Size.Small),
new BrandFilterCriteria(Brand.AmazonBasics)
)))
{
Console.WriteLine(product);
}
Console.ReadKey();
}
}
}
<file_sep>/ConsoleApp1/VisitorPattern.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp12
{
public interface IElement
{
void Accept(IVisitor visitor);
}
public class ConcreteElementA : IElement
{
void IElement.Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
public interface IVisitor
{
void Visit(ConcreteElementA a);
}
public class VisitorPattern
{
public static void Main11(string[] args)
{
}
}
}
| e48e4064bbb1696acd6caebfad88cd891bef98b1 | [
"C#"
] | 9 | C# | aadesh0928/DesignPatternConsole | 65c3692568d1e5ebf945f9419018e136c472aaaf | 6fc2bbc29b3d090c53a154e88921c0de97608e18 |
refs/heads/master | <file_sep>if(typeof require === 'function') {
const buster = require("buster")
, CustomEventEmitter = require("../lib/emitters/custom-event-emitter")
, Helpers = require('./buster-helpers')
, config = require(__dirname + "/config/config")
, dialect = Helpers.getTestDialect()
}
buster.spec.expose()
buster.testRunner.timeout = 1000
var Sequelize = require(__dirname + '/../index')
describe(Helpers.getTestDialectTeaser("Configuration"), function() {
describe('Connections problems should fail with a nice message', function() {
it('should give us an error for not having the correct server details', function(done) {
var domain
try {
domain = require('domain')
} catch (err) {
console.log('WARNING: Configuration specs requires Node version >= 0.8')
expect('').toEqual('') // Silence Buster!
done()
}
var d = domain.create()
var sequelize = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect: dialect})
d.add(sequelize.query)
d.on('error', function(err){
d.remove(sequelize.query)
var msg = 'Failed to find SQL server. Please double check your settings.'
if (dialect === "postgres" || dialect === "postgres-native") {
msg = 'Failed to find PostgresSQL server. Please double check your settings.'
}
else if (dialect === "mysql") {
msg = 'Failed to find MySQL server. Please double check your settings.'
}
expect(err.message).toEqual(msg)
done()
})
d.run(function(){
sequelize.query('select 1 as hello')
.success(function(){})
})
})
it('should give us an error for not having the correct login information', function(done) {
if (dialect !== "postgres" && dialect !== "postgres-native" && dialect !== "mysql") {
// This dialect doesn't support incorrect login information
expect('').toEqual('') // Silence Buster
return done()
}
var domain
try {
domain = require('domain')
} catch (err) {
console.log('WARNING: Configuration specs requires Node version >= 0.8')
expect('').toEqual('') // Silence Buster!
done()
}
var d = domain.create()
var sequelize = new Sequelize(config[dialect].database, config[dialect].username, 'fakepass123', {logging: false, host: config[dialect].host, port: 1, dialect: dialect})
d.add(sequelize.query)
d.on('error', function(err){
d.remove(sequelize.query)
var msg = 'Failed to authenticate for SQL. Please double check your settings.'
if (dialect === "postgres" || dialect === "postgres-native") {
msg = 'Failed to authenticate for PostgresSQL. Please double check your settings.'
}
else if (dialect === "mysql") {
msg = 'Failed to authenticate for MySQL. Please double check your settings.'
}
expect(err.message).toEqual(msg)
done()
})
d.run(function(){
sequelize.query('select 1 as hello')
.success(function(){})
})
})
})
describe('Instantiation with a URL string', function() {
it('should accept username, password, host, port, and database', function() {
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname')
var config = sequelize.config
var options = sequelize.options
expect(options.dialect).toEqual('mysql')
expect(config.database).toEqual('dbname')
expect(config.host).toEqual('example.com')
expect(config.username).toEqual('user')
expect(config.password).toEqual('<PASSWORD>')
expect(config.port).toEqual(9821)
})
it('should work with no authentication options', function() {
var sequelize = new Sequelize('mysql://example.com:9821/dbname')
var config = sequelize.config
expect(config.username).toEqual(undefined)
expect(config.password).toEqual(null)
})
it('should use the default port when no other is specified', function() {
var sequelize = new Sequelize('mysql://example.com/dbname')
var config = sequelize.config
// The default port should be set
expect(config.port).toEqual(3306)
})
})
describe('Intantiation with arguments', function() {
it('should accept two parameters (database, username)', function() {
var sequelize = new Sequelize('dbname', 'root')
var config = sequelize.config
expect(config.database).toEqual('dbname')
expect(config.username).toEqual('root')
})
it('should accept three parameters (database, username, password)', function() {
var sequelize = new Sequelize('dbname', 'root', 'pass')
var config = sequelize.config
expect(config.database).toEqual('dbname')
expect(config.username).toEqual('root')
expect(config.password).toEqual('<PASSWORD>')
})
it('should accept four parameters (database, username, password, options)', function() {
var sequelize = new Sequelize('dbname', 'root', 'pass', { port: 999 })
var config = sequelize.config
expect(config.database).toEqual('dbname')
expect(config.username).toEqual('root')
expect(config.password).toEqual('<PASSWORD>')
expect(config.port).toEqual(999)
})
})
})
<file_sep>if(typeof require === 'function') {
const buster = require("buster")
, Helpers = require('../buster-helpers')
, dialect = Helpers.getTestDialect()
}
buster.spec.expose()
if (dialect.match(/^postgres/)) {
describe('[POSTGRES] hstore', function() {
const hstore = require('../../lib/dialects/postgres/hstore')
describe('stringifyPart', function() {
it("handles undefined values correctly", function() {
expect(hstore.stringifyPart(undefined)).toEqual('NULL')
})
it("handles null values correctly", function() {
expect(hstore.stringifyPart(null)).toEqual('NULL')
})
it("handles boolean values correctly", function() {
expect(hstore.stringifyPart(false)).toEqual('false')
expect(hstore.stringifyPart(true)).toEqual('true')
})
it("handles strings correctly", function() {
expect(hstore.stringifyPart('foo')).toEqual('"foo"')
})
it("handles strings with backslashes correctly", function() {
expect(hstore.stringifyPart("\\'literally\\'")).toEqual('"\\\\\'literally\\\\\'"')
})
it("handles arrays correctly", function() {
expect(hstore.stringifyPart([1,['2'],'"3"'])).toEqual('"[1,[\\"2\\"],\\"\\\\\\"3\\\\\\"\\"]"')
})
it("handles simple objects correctly", function() {
expect(hstore.stringifyPart({ test: 'value' })).toEqual('"{\\"test\\":\\"value\\"}"')
})
it("handles nested objects correctly", function () {
expect(hstore.stringifyPart({ test: { nested: 'value' } })).toEqual('"{\\"test\\":{\\"nested\\":\\"value\\"}}"')
})
it("handles objects correctly", function() {
expect(hstore.stringifyPart({test: {nested: {value: {including: '"string"'}}}})).toEqual('"{\\"test\\":{\\"nested\\":{\\"value\\":{\\"including\\":\\"\\\\\\"string\\\\\\"\\"}}}}"')
})
})
describe('stringify', function() {
it('should handle empty objects correctly', function() {
expect(hstore.stringify({ })).toEqual('')
})
it('should handle null values correctly', function () {
expect(hstore.stringify({ null: null })).toEqual('"null"=>NULL')
})
it('should handle simple objects correctly', function() {
expect(hstore.stringify({ test: 'value' })).toEqual('"test"=>"value"')
})
it('should handle nested objects correctly', function() {
expect(hstore.stringify({ test: { nested: 'value' } })).toEqual('"test"=>"{\\"nested\\":\\"value\\"}"')
})
it('should handle nested arrays correctly', function() {
expect(hstore.stringify({ test: [ 1, '2', [ '"3"' ] ] })).toEqual('"test"=>"[1,\\"2\\",[\\"\\\\\\"3\\\\\\"\\"]]"')
})
it('should handle multiple keys with different types of values', function() {
expect(hstore.stringify({ true: true, false: false, null: null, undefined: undefined, integer: 1, array: [1,'2'], object: { object: 'value' }})).toEqual('"true"=>true,"false"=>false,"null"=>NULL,"undefined"=>NULL,"integer"=>1,"array"=>"[1,\\"2\\"]","object"=>"{\\"object\\":\\"value\\"}"')
})
})
describe('parse', function() {
it('should handle empty objects correctly', function() {
expect(hstore.parse('')).toEqual({ })
})
it('should handle simple objects correctly', function() {
expect(hstore.parse('"test"=>"value"')).toEqual({ test: 'value' })
})
it('should handle nested objects correctly', function() {
expect(hstore.parse('"test"=>"{\\"nested\\":\\"value\\"}"')).toEqual({ test: { nested: 'value' } })
})
it('should handle nested arrays correctly', function() {
expect(hstore.parse('"test"=>"[1,\\"2\\",[\\"\\\\\\"3\\\\\\"\\"]]"')).toEqual({ test: [ 1, '2', [ '"3"' ] ] })
})
it('should handle multiple keys with different types of values', function() {
expect(hstore.parse('"true"=>true,"false"=>false,"null"=>NULL,"undefined"=>NULL,"integer"=>1,"array"=>"[1,\\"2\\"]","object"=>"{\\"object\\":\\"value\\"}"')).toEqual({ true: true, false: false, null: null, undefined: null, integer: 1, array: [1,'2'], object: { object: 'value' }})
})
})
})
}
<file_sep>if(typeof require === 'function') {
const buster = require("buster")
, Sequelize = require("../index")
, Helpers = require('./buster-helpers')
, dialect = Helpers.getTestDialect()
}
buster.spec.expose()
buster.testRunner.timeout = 1000
describe(Helpers.getTestDialectTeaser("Language Util"), function() {
describe("Plural", function(){
before(function(done) {
Helpers.initTests({
dialect: dialect,
onComplete: function(sequelize) {
this.sequelize = sequelize
this.sequelize.options.language = 'es'
done()
}.bind(this)
})
})
it("should rename tables to their plural form...", function(done){
var table = this.sequelize.define('arbol', {name: Sequelize.STRING})
var table2 = this.sequelize.define('androide', {name: Sequelize.STRING})
expect(table.tableName).toEqual('arboles')
expect(table2.tableName).toEqual('androides')
done()
})
it("should be able to pluralize/singularize associations...", function(done){
var table = this.sequelize.define('arbol', {name: Sequelize.STRING})
var table2 = this.sequelize.define('androide', {name: Sequelize.STRING})
var table3 = this.sequelize.define('hombre', {name: Sequelize.STRING})
table.hasOne(table2)
table2.belongsTo(table)
table3.hasMany(table2)
expect(table.associations.androides.identifier).toEqual('arbolId')
expect(table2.associations.arboles).toBeDefined()
expect(table3.associations.androideshombres).toBeDefined()
done()
})
})
})
| 498e349bdad3206fcef61a2147a743f324482a89 | [
"JavaScript"
] | 3 | JavaScript | jlongster/sequelize | cbc7747ce03b214179a576d19e27761e9c192715 | 3aea14070390b11d98d92979628b8c2efcad7a40 |
refs/heads/master | <file_sep>//Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
function titleCase(str) {
str = str.toLowerCase();
str = str.split(" ");
for(var i = 0; i < str.length; i++)
{
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
str = str.join(" ");
return str;
}
titleCase("I'm a little tea pot");
<file_sep>
Various JavaScript Algorithm Challenges
<file_sep>//Return array consisting of the largest number from each provided sub-array.
function NestedLoop(arr) {
var num = 0;
for(var i = 0; i < arr.length; i++)
{
for(var j = 0; j < arr[i].length; j++)
{
if(num < arr[i][j])
num = arr[i][j];
}
arr[i] = num;
num = 0;
}
return arr;
}
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
| 4e0b08125b6471d0c9a4c657338e4e6b3110ca26 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Zach-OfAllTrades/JavaScriptAlgorithms | 5698925dd4372fafd2e04806aa36b13e7dde4541 | 9afccff13f7e6b5484247279659a857a3faba215 |
refs/heads/master | <file_sep><?php
$iHand = $_POST["playerHand"];
$GTP = ["グー","チョキ","パー"];
$key = array_rand($GTP);
$pcHand = $GTP[$key];
if($iHand == $pcHand){
$result = "Draw";
} else if ($iHand == 'グー' && $pcHand == 'チョキ') {
$result = "Victory";
} else if ($iHand == 'チョキ' && $pcHand == 'パー') {
$result = "Victory";
} else if ($iHand == 'パー' && $pcHand == 'グー') {
$result = 'Victory';
} else {
$result = 'Defeat';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>RESULT</title>
<link rel="stylesheet" href="style-battle.css">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<div class="header-logo2">ジャンケン大会</div>
<div class = "resImg">
<?php if($result == "Victory"): ?>
<img src = "wanezumi_pink2.png" height = "480">
<?php elseif($result == "Draw"): ?>
<img src = "wanezumi_kiiro2.png" height = "480">
<?php else: ?>
<img src = "wanezumi_blue2.png" height = "480" class = >
<?php endif ?>
</div>
<p class = "res"><?php echo $result ?></p>
<div class = "handImg">
<?php if($iHand == "グー"): ?>
<img src = "17498.jpg" >
<?php elseif($iHand == "チョキ"): ?>
<img src = "17499.jpg" >
<?php else: ?>
<img src = "17500.jpg" >
<?php endif ?>
<span>vs</span>
<?php if($pcHand == "グー"): ?>
<img src = "17498.jpg" >
<?php elseif($pcHand == "チョキ"): ?>
<img src = "17499.jpg" >
<?php else: ?>
<img src = "17500.jpg" >
<?php endif ?>
</div>
</body>
| 2392961744b4dcf391f5ca874b0e207c4f1aeef4 | [
"PHP"
] | 1 | PHP | hcra-12/Janken-Website | 7b6fbd66aa998a1684ff0c67bdef202c3f6243ec | 7e2e19404940a495d94a8d72bb532b5b056b32fd |
refs/heads/master | <repo_name>regnstr/led-backend<file_sep>/index.js
const express = require('express');
const morgan = require('morgan');
const moment = require('moment');
const _ = require('lodash');
const chalk = require('chalk');
require('log-timestamp')(() => '[' + chalk.gray(moment().format(moment.HTML5_FMT.DATETIME_LOCAL_MS)) + ']');
const fs = require('fs').promises;
const app = express();
const cors = require('cors');
const axios = require('axios');
const NUM_LEDS = 1000;
const initialData = Array(NUM_LEDS).fill(false);
let ledData = initialData;
let index = 0;
setInterval(() => {
ledData[index] = !ledData[index];
index++;
if(index == NUM_LEDS) {
index = 0;
}
}, 1000);
function toggleLed(index) {
ledData[index] = !ledData[index];
}
// Use 'dev' for logging
app.use(morgan('dev'));
app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
res.send(JSON.stringify(ledData));
});
app.post('/', (req, res) => {
//console.log(req.body);
console.log(req.body.index);
toggleLed(req.body.index);
res.send(JSON.stringify(ledData));
});
const PORT = 5001;
// run the server
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
}); | 54db113907015f3c196a85ca349143c636af04e3 | [
"JavaScript"
] | 1 | JavaScript | regnstr/led-backend | 667978a8f6237e87e39a7cb19598752d7d60c715 | 585702cfd61981346ff76178ace6514c5da75b40 |
refs/heads/main | <file_sep>''' soma = 10 + 10
subtracao = 20 - 10
divisao = 100/10
multiplicacao = 2 * 40'''
#print(10+10)
#print(10 + (50 + 50))
print(10 - 10)
print(1000 - 80)
print(10 / 5)
print(10 / 6)
print(10 // 6) #remove as casas decimais.
print(10 * 800)
print(55 * 5)
<file_sep>print('parametro')<file_sep># Utilizamos as tomadas de decisões para alterar o fluxo do nosso programa.
a = 10
if(a==10):
print("O valor de a é igual a 10")<file_sep>''' Característica das variáveis em Python:
1) um nome;
2) um tipo;
3) um tamanho;
4) um valor.
Estrutura de declaração da variável:
nome = valor
nome se refere ao nome da variável
valor refere ao valor a ser atribuído a variável'''
num = 20
type(num)
dinheiro = 15.55
type(dinheiro)<file_sep># resto da divisão: % exemplo: 6 / 2 = 0; 3 / 2 = 1.
'''print(3%2)
print(4%2)
print(7%3.1)
print(900%100==0)'''
num1 = float(input("Digite um número: "))
num2 =float(input("Digite outro número: "))
divisao = num1 / num2
resto = num1 % num2
print()
print(num1, "dividido por", num2, "é igual a: ", divisao)
print("o resto da divisão entre", num1, "e", num2, "é igual a:", resto)<file_sep>''' Operadores de atribuições - O valor ao aldo direito do operador é atribuido
à variável a esquerda do operador.
nome = valor
nome --> variável valor --> valor a ser atribuído
= atribui
== iguala/compara
atribuição - x = y
comparação - x == y'''
a = 9
x = y = z = a
print(a)
x == y == z == a
print(a)<file_sep># python_eXcript
Esse é um curso completo de Python da plataforma do youtube eXcript. Neste, nós aprenderemos do básico ao avançado sobre como programar em Python. Cada aula do curso foi projetada para interagir a prender de forma ampla a linguagem.
<file_sep>''' Operadores de atribuição
x = 9
y = 3
+= -> (x += y) = 12
-= -> (x -= y) = 6
*= -> (x *= y) = 27
/= -> (x /= y) = 3
%= -. (x %= y) = 0'''
x = 9
y = 3
x += y
print(x)
x = 9
y = 3
x -= y
print(x)
x = 9
y = 3
x *= y
print(x)
x = 9
y = 3
x /= y
print(x)
x = 9
y = 3
x %= y
print(x)<file_sep>''' laço de repetição for... in...:
for <var> in <lista>:
...
...
...
'''
for c in 'eXcript':
print(c)
for c in 'python':
print(c)
<file_sep>''' O que é uma variável?
Local de memória reservado, utilizado para armazenar alguma
informação - um valor. '''
a = 10
b = 25
a + b
texto = 'todo texto é uma string'<file_sep>#5**2 - potência de um número.
#81**(1/2) -> radiciação<file_sep>''' Instrução break: A instrução break interrompe a execução do laço de repetição
onde está contido. '''<file_sep>'''
print("Aprendendo como utilizar comentários")
print("segunda linha")
'''
print("terceira linha") #aqui é um comentário que não será interpretado.<file_sep>idade = int(input("Informe a sua idade: "))
if(idade <= 0):
print("A sua idade não pode ser 0 ou menor do que 0!")
elif(idade > 150):
print("A sua idade não pode ser superior a 150 anos!")
elif(idade < 18):
print("Você precisa ter mais do que 18 anos!")<file_sep>''' Atribuição múltipla é a capacidade de atribuir valores diferentes a variáveis
distintas numa mesma instrução.
Exemplos:
a, b , c = 5, 7, 9
s1, s2 = 'curso', 'python'
Vamos ver como funciona isto:
a = 10
b = 5
a, b = b, a
Outro exemplo:
x, y = 2, 4 => x está para 2 e y está para 4
Exemplo de atribuição múltipla
x, y, z = 2, 4, 8
x, y, z = x*2, x+y+z, x*y*z
x = 2*2 = 04
y = 2+4+8 = 14
z = 2*4*8 = 64'''
a, b, c = 2, 4, 8
a, b, c = a*2, a+b+c, a*b*c
print(a,b,c)
nome, sobrenome = "José", " <NAME>"
print(nome + sobrenome)
<file_sep>'''Lembrando que o programa abaixo é só um exemplo de função!
não conseguimos acessar as var do bloco 2, 3 e 4 pelo nível 1. Somente o
contrário.
Cada bloco de instruções só consegue acessar o que for parte do seu escopo, ou o
escopo universal que é o 1.
O bloco 1 ou escopo 1 é a parte universal do programa, ele interage com todos
os outros blocos. '''
# bloco 1 - escopo 1.
a = 1
b = 2
# bloco 2 - escopo 2: aqui pode acessar todas as funções que estão no bloco 1
def soma_num(var1, var2):
s = var1 + var2
return s
# bloco 3 - escopo 3: aqui tb o escopo pode ser chamado
def imprime(x_vezes):
for i in range(x_vezes):
print(i) # bloco 4 - escopo 4: aqui será printada as inf. q foram chamadas.
print(soma_num(a, b))
imprime(5)<file_sep>numero_inteiro = 5
numero_decimal = 7.3
valor_string = "qualquer texto"
print("O valor é:", numero_inteiro)
print("O valor é: %i" %numero_inteiro)
print("O valor é: " + str(numero_inteiro))
print("Concatenando decimal:", numero_decimal)
print("Concatenando decimal: %.2f" %numero_decimal)
print("Concatenando decimal:" + str(numero_decimal))
print("Concatenando strings:", valor_string)
print("Concatenando strings:%s" %valor_string)
print("Concatenando strings:" + valor_string)<file_sep>login = input("Login:")
senha = input("Senha:")
print("O usuário informado foi: %s, e a senha digitada foi: %s" %(login, senha))<file_sep>''' Indentação é o padrão utilizado para organizar um grupo de códigos.
Indentar é espacejar linha, parágrafo, (...) Da margem esquerda a direita
em folha a ser impressa, etc (<NAME>).'''
if True:
print("Oi")
print("Oi"); print("Tchau"); #o uso de ; não é recomendado nessa linguagem!<file_sep># Manipulação de dados
numero_inteiro = 5
numero_decimal = 7.3
valor_string = "qualquer texto"
print("O valor é:", numero_inteiro)
print("O valor é: %i" %numero_inteiro)
print("O valor é: " + str(numero_inteiro))<file_sep>''' Atribuição condicional é uma estrutura utilizada para simplificar o código,
onde o valor a ser atrbuído será aquele que satisfazer a condição.
<variável> = <valor1> if (True) else <valor2>
var = 10 if (True) else 20
x = 10
texto = 'sim' if x == 10 else 'não'
print(texto)
x = 9
texto = 'sim' if x == 10 else 'não'
print(texto)'''
###################### PROGRAMA 1 ###############
num1 = int(input("Digite um número:"))
s = 'par' if num1 %2 == 0 else 'ímpar'
print('O número digitado é: ', s)
<file_sep>''' and - e
or - ou
not - negação
is - é
is not - não é
in - está contido
not in - não está contido '''
print(2<4 and 2==4)
print(2>4 or 2<4)
print(not(2>5 or 2<4))
print(2 is 2)
print(type(2))
print(type(2) is int)
print(type(2.0) is int)
print(type(2.0))
print(type(2.0) is float)
<file_sep>acao = int(input("Digite '1' para sim e digite '2' para não: "))
if(acao == 1):
print("Você disse que sim!")
else:
if(acao == 2):
print("Você disse que não!")
else:
print("O número digitado não é '1' e nem '2'!!!! ")<file_sep># range ([start], stop[, step])
list(range(10))
list(range(1, 15))
list(range(0, 100, 10))
list(range(0, 100, 3))
list(range(100, 0, -3))
list(range(-100, 0, 3))
print(list(range(10)))
print(list(range(1, 15)))
print(list(range(0, 100, 10)))
print(list(range(0, 100, 3)))
print(list(range(100, 0, -3)))
print(list(range(-100, 0, 3)))
# agor veremos range com for
for i in range(10): #aqui queremos que o programa vai do 1 até o zero.
print(i)
# a forma abaixo é a melhor para trabalhar a função range com for.
for i in range(-10, 0, 1): # aqui queremos que o -10 chegue a zero indo de 1 em 1.
print(i)
<file_sep>if(True):
print("Imprime um texto")
print("Imprime um texto")
print("Imprime um texto")
print("Imprime um texto")
if(False):
print("Não irá imprimir")
print("Não irá imprimir")
print("Não irá imprimir")
print("Não irá imprimir")
print("Não irá imprimir")<file_sep>''' Há regras para nomes de variáveis, métodos e classes?
Caracteres:
minha_variavel
valor_total
Pode iniciar com: a...z e _
Pode conter: a..z, 0...9, _
Evitar utilizar os caracteres:
1) I
2) O
que podem confundir
pacote/Módulos:
- utilizar nome pequenos
- utilizar caratere minúsculos
Exemplos: -os - package
Classes:
- iniciar com letra minúscula
- nomes compostos com ambas palavras em maiúscula
Exemplos: -RioSete
-NomeDaClasse
Funções/Métodos
-letras minúsculas
-nomes compostos unidos por underscore(_)
Exemplos: - utilizar_underscore()
- enviar_email()
Constantes:
- letras maiúsculas;
- nomes compostos por undescore(_);
Exemplos:
- PI
- VALOR_MAXIMO
Parâmetro de função:
-letras minúsculas
-nomes compostos unidos por underscore(_)
Exemplos: -enviar(nome_do_arquivo)
- receber(self) '''
receber = 10 + 2
print(receber)<file_sep>''' Iteração é o processo de repetição onde um bloco de instrução é executado
enquanto uma condição for atendida'''
x = 0
while(x <= 10):
print(x)
x += 1
<file_sep>''' Operadores relacionais são utilizados para verificar condições e julgarem:
- se são verdadeiras
- ou falsas
Operadores de igualdade
(=) Igualdade: ==
(/=) Diferente: !=
(x == y) -> x é igual a y;
(x != y) -> x é diferente de y.'''
print(100 == 100)
print('a' == 'a')
print (100 != 100)
print(5 < 5) or (5==5.1)<file_sep>''' range ([start], stop[, step])
x[, ]y, z
0, 4
{1, 2, 3}
[x, y]
0, 4
(0,1,2,3,4) '''
range(0, 10, 2)
type(range(0, 10, 2))
list(range(0, 10, 2))
list(range(10))
print(range (0, 10, 2))
print(type(range(0, 10, 2)))
print(list(range(0, 10, 2)))
print(list(range(10)))<file_sep>num1 = int(input("Digite um número: "))
if(num1 > 10):
print("O valor é maior do que 10!")
if(num1 <= 15):
print("O valor é maior do que 10, mas menor do que 15!")
else:
if(num1 <= 50):
print("O valor é maior do que 10, mas menor do que 50!")
else:
print("O valor é maior do que 50!")
else:
if(num1 > 5):
print("O número é menor do que 10, mas maior do que 5!")
if(num1 == 7):
print("O número é igual a 7!")
else:
print("O valor é igual ou menor do que 5!") <file_sep>numero1 = input("Digite um número:")
numero1 = int(numero1)
numero2 = input("Digite um segundo número:")
numero2 = int(numero2)
if(numero1 == numero2): #operador de igualdade
print("O número %d é igual a %d. "%(numero1, numero2))
if(numero1 != numero2): #operador de diferença
print("O número %d é diferente de %d. "%(numero1, numero2))
if(numero1 < numero2): #operador menor que
print("O número %d é menor que o %d. "%(numero1, numero2))
if(numero1 <= numero2): #operador menor ou igual que
print("O número %d é menor ou igual a %d. "%(numero1, numero2))
if(numero1 > numero2): #operador maior que
print("O número %d é maior que o %d. "%(numero1, numero2))
if(numero1 >= numero2): #operador maior ou igual que
print("O número %d é maior ou igual que %d. "%(numero1, numero2)) | a67fa677463858f0eee115187d886eb794bae4c0 | [
"Markdown",
"Python"
] | 31 | Python | robinson-1985/python_eXcript | fbb44b1881b8458106f82722c3d1a5bef8403240 | 25132d6d308e99f4ebea48e13910c52f3bd65026 |
refs/heads/main | <file_sep>spring.activemq.broker-url=tcp://localhost:61616
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
weather.api=http://api.weatherapi.com/v1/current.json?
weather.apikey=871874c7aaea46fdb0e173504210102<file_sep>package com.mq.ActiveMQ.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mq.ActiveMQ.entity.Weather;
@Service
public class ProducerService {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Value("${weather.api}")
private String weatherapi;
@Value("${weather.apikey}")
private String weatherapikey;
public Weather currentWeather(String place) throws IOException{
Logger logger = Logger.getLogger("PRODUCEER");
logger.log(Level.INFO, "Invoking Producer");
URL url = new URL(weatherapi+"key=" + weatherapikey+"&q="+ place);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("accept", "application/json");
InputStream responseInputStream = connection.getInputStream();
ObjectMapper mapper = new ObjectMapper();
Weather weather = mapper.readValue(responseInputStream, Weather.class);
this.jmsMessagingTemplate.convertAndSend(this.queue, weather);
return weather;
}
}
<file_sep>package com.mq.ActiveMQ.controller;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.mq.ActiveMQ.entity.Weather;
import com.mq.ActiveMQ.service.ProducerService;
@RestController
public class ProducerController {
@Autowired
public ProducerService producerService;
@GetMapping("currentWeather/{place}")
public Weather currentWeather(@PathVariable String place) throws IOException{
return producerService.currentWeather(place);
}
}
| 261590f07b225dc1543c1dcce565202568fff9c6 | [
"Java",
"INI"
] | 3 | INI | sushmitha-gopari/ActiveMQ | 8f06f038665ca1b9c2b2e035f45b823936c70074 | cd7370efef91c8bb6bdb092ce6f5661075b424ed |
refs/heads/master | <repo_name>c-villain/GoFPatterns<file_sep>/README.md
# GoFPatterns
Patterns of GoF and its realization on Swift
Репозиторий представляет из себя Playground книгу с кратким описанием паттернов из книги ["банды четырех"](https://ru.wikipedia.org/wiki/Design_Patterns).
Рассмотрены примеры, когда целесообразно применять тот или иной паттерн, а также основные участники в нем.
Описание дополнено примерами на Swift.
## Creational
- Builder
- Abstract factory
- Factory method
- Prototype
- Singleton
## Structural
- Adapter
- Bridge
- Composite
- Decorator
- Facade
- Flyweight
- Proxy
- Behavioral
## Command
- Chain of responsibility
- Interpreter
- Iterator
- Mediator
- Memento
- Observer
- State
- Strategy
- Template method
- Visitor
## Special thanks
- [Рефакторинг.Гуру](https://refactoring.guru)
- [Metanit](https://metanit.com)
<file_sep>/GoFPatterns.playground/Pages/StructuralPatterns.xcplaygroundpage/Contents.swift
//: [к содержанию](Intro)
//:
//: [к порождающим паттернам](CreationalPatterns)
//:
//: [к поведенеческим паттернам](BehavioralPatterns)
import Foundation
//: # _Структурные паттерны_
//:
//: ## _Adapter (wrapper)_
//: ### Адаптер — это структурный паттерн проектирования, который позволяет объектам с несовместимыми интерфейсами работать вместе.
//:Участники:
//: * Target: представляет объекты, которые используются клиентом (класс, к которому надо адаптировать другой класс )
//: * Client: использует объекты Target для реализации своих задач
//: * Adaptee: представляет адаптируемый класс, который мы хотели бы использовать у клиента вместо объектов Target
//: * Adapter: собственно адаптер, который позволяет работать с объектами Adaptee как с объектами Target.
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/adapter) и [тут](https://metanit.com/sharp/patterns/4.2.php)
///Target
protocol Driveable{
func drive()
}
protocol Traveller{
func travel(transport: Driveable)
}
///Client
struct Man: Traveller
{
func travel(transport: Driveable)
{
transport.drive();
}
}
struct Auto: Driveable {
func drive()
{
print("Car is driving on road");
}
}
protocol Moveable{
func move()
}
///Adaptee
struct Camel: Moveable {
func move()
{
print("Camel is moving on sand");
}
}
///Adapter
class CamelToTransportAdapter : Driveable
{
var camel: Camel
init(camel: Camel){
self.camel = camel
}
func drive(){
self.camel.move()
}
}
let man = Man()
let auto = Auto()
man.travel(transport: auto)
let camel = Camel()
let camelAdapter = CamelToTransportAdapter(camel: camel)
man.travel(transport: camelAdapter)
//: ## _Bridge_
//: ### Мост — это структурный паттерн проектирования, который разделяет один или несколько классов на две отдельные иерархии — абстракцию и реализацию, позволяя изменять их независимо друг от друга.
//: ### Когда использовать данный паттерн?
//: * Когда надо избежать постоянной привязки абстракции к реализации
//: * Когда наряду с реализацией надо изменять и абстракцию независимо друг от друга. То есть изменения в абстракции не должно привести к изменениям в реализации
//: ### Участники
//: * Abstraction: определяет базовый интерфейс и хранит ссылку на объект Implementor. Выполнение операций в Abstraction делегируется методам объекта Implementor
//: * RefinedAbstraction: уточненная абстракция, наследуется от Abstraction и расширяет унаследованный интерфейс
//: * Implementor: определяет базовый интерфейс для конкретных реализаций. Как правило, Implementor определяет только примитивные операции. Более сложные операции, которые базируются на примитивных, определяются в Abstraction
//: * ConcreteImplementorA и ConcreteImplementorB: конкретные реализации, которые унаследованы от Implementor
//: * Client: использует объекты Abstraction
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/bridge) и [тут](https://metanit.com/sharp/patterns/4.6.php)
///Implementor
protocol Language{
func Build()
func Execute()
}
///ConcreteImplementorA
struct CPPLanguage : Language{
func Build(){
print("С помощью компилятора C++ компилируем программу в бинарный код");
}
func Execute(){
print("Запускаем исполняемый файл программы");
}
}
///ConcreteImplementorB
struct SwiftLanguage : Language{
func Build(){
print("С помощью компилятора Apple LLVM компилируем исходный код");
}
func Execute(){
print("Запускаем .ipa файл");
}
}
///Abstraction
protocol Programmer{
var language: Language { get set }
func doWork()
func earnMoney()
}
extension Programmer{
func doWork(){
self.language.Build()
self.language.Execute()
}
}
///RefinedAbstraction
struct FreelanceProgrammer: Programmer{
var language: Language
func earnMoney() {
print("Получаем оплату за выполненный заказ")
}
}
///RefinedAbstraction
struct CorporateProgrammer : Programmer{
var language: Language
func earnMoney() {
print("Получаем в конце месяца зарплату");
}
}
// создаем нового программиста, он работает с с++
var freelancer: Programmer = FreelanceProgrammer(language: CPPLanguage());
freelancer.doWork()
freelancer.earnMoney()
// пришел новый заказ, но теперь нужен swift
freelancer.language = SwiftLanguage();
freelancer.doWork();
freelancer.earnMoney();
//: ## _Composite_
//: ### Компоновщик — это структурный паттерн проектирования, который позволяет сгруппировать множество объектов в древовидную структуру, а затем работать с ней так, как будто это единичный объект.
//: Паттерн Компоновщик (Composite) объединяет группы объектов в древовидную структуру по принципу "часть-целое и позволяет клиенту одинаково работать как с отдельными объектами, так и с группой объектов.
//:
//: Паттерн Компоновщик имеет смысл только тогда, когда основная модель вашей программы может быть структурирована в виде дерева.
//:
//: Например, есть два объекта: Продукт и Коробка. Коробка может содержать несколько Продуктов и других Коробок поменьше. Те, в свою очередь, тоже содержат либо Продукты, либо Коробки и так далее.
//: ### Участники
//: * Component: определяет интерфейс для всех компонентов в древовидной структуре
//: * Composite: представляет компонент, который может содержать другие компоненты и реализует механизм для их добавления и удаления
//: * Leaf: представляет отдельный компонент, который не может содержать другие компоненты
//: * Client: клиент, который использует компоненты
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/composite) и [тут](https://metanit.com/sharp/patterns/4.4.php)
///Component
protocol Vehicle{
mutating func drive()
}
///Leaf
struct Car: Vehicle{
mutating func drive(){
print("Drive car")
}
}
struct Truck: Vehicle{
mutating func drive(){
print("Drive truck")
}
}
struct Bus: Vehicle{
mutating func drive(){
print("Drive bus")
}
}
///Composite
struct CarPark: Vehicle{
private var vehicles = [Vehicle]()
init(vehicles: Vehicle...){
self.vehicles = vehicles
}
mutating func drive(){
for var vehicle in self.vehicles{
vehicle.drive()
}
}
}
var carPark = CarPark(vehicles: Bus(), Truck(), Car())
carPark.drive()
//: ## _Decorator_
//: ### Декоратор — это структурный паттерн проектирования, который позволяет динамически добавлять объектам новую функциональность, оборачивая их в полезные «обёртки».
//: Для определения нового функционала в классах нередко используется наследование. Декораторы же предоставляет наследованию более гибкую альтернативу, поскольку позволяют динамически в процессе выполнения определять новые возможности у объектов.
//: ### Участники
//: * Component: абстрактный класс, который определяет интерфейс для наследуемых объектов
//: * ConcreteComponent: конкретная реализация компонента, в которую с помощью декоратора добавляется новая функциональность
//: * Decorator: собственно декоратор, реализуется в виде абстрактного класса и имеет тот же базовый класс, что и декорируемые объекты. Поэтому базовый класс Component должен быть по возможности легким и определять только базовый интерфейс. Класс декоратора также хранит ссылку на декорируемый объект в виде объекта базового класса Component и реализует связь с базовым классом как через наследование, так и через отношение агрегации.
//: * Классы ConcreteDecoratorA и ConcreteDecoratorB представляют дополнительные функциональности, которыми должен быть расширен объект ConcreteComponent.
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/decorator) и [тут](https://metanit.com/sharp/patterns/4.1.php)
///Component
protocol Pizza{
var name: String { get }
func getCost() -> Int
}
///ConcreteComponent
struct ItalianPizza: Pizza{
var name: String
func getCost() -> Int{
return 10
}
init(){
self.name = "Итальянская пицца"
}
}
///ConcreteComponent
struct BulgerianPizza: Pizza{
var name: String
func getCost() -> Int{
return 8
}
init(){
self.name = "Болгарская пицца"
}
}
///Decorator
protocol PizzaDecorator : Pizza{
var pizza: Pizza { get }
func getCost() -> Int
}
///ConcreteDecoratorA
struct TomatoPizza : PizzaDecorator{
var name: String{
return self.pizza.name + " с томатами"
}
let pizza: Pizza
func getCost() -> Int{
return pizza.getCost() + 3;
}
}
///ConcreteDecoratorB
struct CheesePizza : PizzaDecorator{
let pizza: Pizza
var name: String{
return self.pizza.name + " с сыром"
}
func getCost() -> Int{
return pizza.getCost() + 5;
}
}
var pizza1: Pizza = ItalianPizza();
pizza1 = TomatoPizza(pizza: pizza1); // итальянская пицца с томатами
print("Name: \(pizza1.name), price: \(pizza1.getCost())")
var pizza2: Pizza = ItalianPizza();
pizza2 = CheesePizza(pizza: pizza2);// итальянская пиццы с сыром
print("Name: \(pizza2.name), price: \(pizza2.getCost())")
var pizza3: Pizza = BulgerianPizza();
pizza3 = TomatoPizza(pizza: pizza3);
pizza3 = CheesePizza(pizza: pizza3);// болгарская пиццы с томатами и сыром
print("Name: \(pizza3.name), price: \(pizza3.getCost())")
//: ## _Facade_
//: ### Фасад — это структурный паттерн проектирования, который предоставляет простой интерфейс к сложной системе классов, библиотеке или фреймворку.
//: Когда использовать фасад?
//: * Когда имеется сложная система, и необходимо упростить с ней работу. Фасад позволит определить одну точку взаимодействия между клиентом и системой.
//: * Когда надо уменьшить количество зависимостей между клиентом и сложной системой. Фасадные объекты позволяют отделить, изолировать компоненты системы от клиента и развивать и работать с ними независимо.
//: * Когда нужно определить подсистемы компонентов в сложной системе. Создание фасадов для компонентов каждой отдельной подсистемы позволит упростить взаимодействие между ними и повысить их независимость друг от друга.
//: ### Участники
//: * Классы SubsystemA, SubsystemB, SubsystemC и т.д. являются компонентами сложной подсистемы, с которыми должен взаимодействовать клиент
//: * Client взаимодействует с компонентами подсистемы
//: * Facade - непосредственно фасад, который предоставляет интерфейс клиенту для работы с компонентами
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/facade) и [тут](https://metanit.com/sharp/patterns/4.3.php)
///SubsystemA
struct FrontEndCompileStage{
func parse(){
print("Парсить код и строить абстрактное дерево - abstract semantic tree (AST)")
}
func sema(){
print("Провести семантический анализ")
}
func silGen(){
print("Сгенерировать SIL - Swift Intermediate Language")
}
}
///SubsystemB
struct MiddleEndCompilerStage{
func silOptimize(){
print("Провести оптимизацию SIL")
}
func irGen(){
print("Сгенерировать промежуточное представление для LLVM")
}
}
///SubsystemC
struct BackEndComplilerStage{
func codeGenerate(){
print("Сгенерировать ассембли код и моздать исполняемый файл")
}
}
///Facade
struct CompilerFacade{
let front: FrontEndCompileStage
let middle: MiddleEndCompilerStage
let back: BackEndComplilerStage
func compile(){
front.parse()
front.sema()
front.silGen()
middle.silOptimize()
middle.irGen()
back.codeGenerate()
}
}
///Client
struct Xcode{
func compileApp(compiler: CompilerFacade){
compiler.compile()
}
}
let xcode = Xcode()
xcode.compileApp(compiler: CompilerFacade(front: FrontEndCompileStage(), middle: MiddleEndCompilerStage(), back: BackEndComplilerStage()))
//: ## _Proxy_
//: ### Заместитель — это структурный паттерн проектирования, который позволяет подставлять вместо реальных объектов специальные объекты-заменители. Эти объекты перехватывают вызовы к оригинальному объекту, позволяя сделать что-то до или после передачи вызова оригиналу.
//: Когда использовать прокси?
//: * Когда надо осуществлять взаимодействие по сети, а объект-проси должен имитировать поведения объекта в другом адресном пространстве. Использование прокси позволяет снизить накладные издержки при передачи данных через сеть. Подобная ситуация еще называется удалённый заместитель (remote proxies)
//: * Когда нужно управлять доступом к ресурсу, создание которого требует больших затрат. Реальный объект создается только тогда, когда он действительно может понадобится, а до этого все запросы к нему обрабатывает прокси-объект. Подобная ситуация еще называется виртуальный заместитель (virtual proxies)
//: * Когда необходимо разграничить доступ к вызываемому объекту в зависимости от прав вызывающего объекта. Подобная ситуация еще называется защищающий заместитель (protection proxies)
//: * Когда нужно вести подсчет ссылок на объект или обеспечить потокобезопасную работу с реальным объектом. Подобная ситуация называется "умные ссылки" (smart reference)
//: ### Участники
//: * Subject: определяет общий интерфейс для Proxy и RealSubject. Поэтому Proxy может использоваться вместо RealSubject
//: * RealSubject: представляет реальный объект, для которого создается прокси
//: * Proxy: заместитель реального объекта. Хранит ссылку на реальный объект, контролирует к нему доступ, может управлять его созданием и удалением. При необходимости Proxy переадресует запросы объекту RealSubject
//: * Client: использует объект Proxy для доступа к объекту RealSubject
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/facade) и [тут](https://metanit.com/sharp/patterns/4.3.php)
//: ### Protection proxy example:
///Subject
protocol DoorOpening {
func open(doors: String) -> String
}
///RealSubject
final class HAL9000: DoorOpening {
func open(doors: String) -> String {
return ("HAL9000: Affirmative, Dave. I read you. Opened \(doors).")
}
}
///Proxy
final class CurrentComputer: DoorOpening {
private var computer: HAL9000!
func authenticate(password: String) -> Bool {
guard password == "<PASSWORD>" else {
return false
}
computer = HAL9000()
return true
}
func open(doors: String) -> String {
guard computer != nil else {
return "Access Denied. I'm afraid I can't do that."
}
return computer.open(doors: doors)
}
}
let computer = CurrentComputer()
let podBay = "Pod Bay Doors"
print(computer.open(doors: podBay))
computer.authenticate(password: "<PASSWORD>")
print(computer.open(doors: podBay))
//: ### Virtual proxy example:
///Subject
protocol HEVSuitMedicalAid {
func administerMorphine() -> String
}
///RealSubject
final class HEVSuit: HEVSuitMedicalAid {
func administerMorphine() -> String {
return "Morphine administered."
}
}
///Proxy
final class HEVSuitHumanInterface: HEVSuitMedicalAid {
lazy private var physicalSuit: HEVSuit = HEVSuit()
func administerMorphine() -> String {
return physicalSuit.administerMorphine()
}
}
let humanInterface = HEVSuitHumanInterface()
print(humanInterface.administerMorphine())
//: ## _Flyweight_
//: ### Легковес — это структурный паттерн проектирования, который позволяет вместить бóльшее количество объектов в отведённую оперативную память. Легковес экономит память, разделяя общее состояние объектов между собой, вместо хранения одинаковых данных в каждом объекте.
//: Когда использовать легковес?
//: * Когда приложение использует большое количество однообразных объектов, из-за чего происходит выделение большого количества памяти
//: * Когда часть состояния объекта, которое является изменяемым, можно вынести во вне. Вынесение внешнего состояния позволяет заменить множество объектов небольшой группой общих разделяемых объектов.
//: ### Участники
//: * Flyweight: определяет интерфейс, через который приспособленцы-разделяемые объекты могут получать внешнее состояние или воздействовать на него
//: * ConcreteFlyweight: конкретный класс разделяемого приспособленца. Реализует интерфейс, объявленный в типе Flyweight, и при необходимости добавляет внутреннее состояние. Причем любое сохраняемое им состояние должно быть внутренним, не зависящим от контекста
//: * UnsharedConcreteFlyweight: еще одна конкретная реализация интерфейса, определенного в типе Flyweight, только теперь объекты этого класса являются неразделяемыми
//: * FlyweightFactory: фабрика приспособленцев - создает объекты разделяемых приспособленцев. Так как приспособленцы разделяются, то клиент не должен создавать их напрямую. Все созданные объекты хранятся в пуле. Однако в зависимости от сложности структуры, хранящей разделяемые объекты, особенно если у нас большое количество приспособленцев, то может увеличиваться время на поиск нужного приспособленца - наверное это один из немногих недостатков данного паттерна. Если запрошенного приспособленца не оказалось в пуле, то фабрика создает его.
//: * Client: использует объекты приспособленцев. Может хранить внешнее состояние и передавать его в качестве аргументов в методы приспособленцев
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/facade) и [тут](https://metanit.com/sharp/patterns/4.3.php)
///Flyweight
protocol House{
var stages: Int { get } // количество этажей
func build(longitude: Double,latitude: Double)
}
///ConcreteFlyweight
struct PanelHouse : House{
var stages: Int
func build(longitude: Double, latitude: Double) {
print("Построен панельный дом из 16 этажей; координаты: \(longitude) широты и \(latitude) долготы")
}
init(){
self.stages = 16
}
}
///UnsharedConcreteFlyweight
struct BrickHouse : House{
var stages: Int
init(){
self.stages = 5
}
func build(longitude: Double, latitude: Double) {
print("Построен кирпичный дом из 5 этажей; координаты: \(longitude) широты и \(latitude) долготы")
}
}
///FlyweightFactory
class HouseFactory{
private var houses: [String: House] = [:]
init(){
houses["Panel"] = PanelHouse()
houses["Brick"] = BrickHouse()
}
func getHouse(key: String)-> House? {
guard houses.index(forKey: key) != nil else {return nil}
return houses[key]
}
}
var longitude = 37.61
var latitude = 55.74
var houseFactory = HouseFactory()
for _ in 1...5 {
let panelHouse = houseFactory.getHouse(key: "Panel")
if (panelHouse != nil){
panelHouse!.build(longitude: longitude, latitude: latitude)
longitude += 0.1
latitude += 0.1
}
}
for _ in 1...5{
let brickHouse = houseFactory.getHouse(key: "Brick")
if (brickHouse != nil){
brickHouse!.build(longitude: longitude, latitude: latitude)
longitude += 0.1
latitude += 0.1
}
}
//:
//: [к содержанию](Intro)
//:
//: [к порождающим паттернам](CreationalPatterns)
//:
//: [к поведенеческим паттернам](BehavioralPatterns)
//:
<file_sep>/GoFPatterns.playground/Pages/Intro.xcplaygroundpage/Contents.swift
//: # _Паттерны_
//: ### Паттерн проектирования — это часто встречающееся решение определённой проблемы при проектировании архитектуры программ.
//:
//: ### В отличие от готовых функций или библиотек, паттерн нельзя просто взять и скопировать в программу. Паттерн представляет собой не какой-то конкретный код, а общую концепцию решения той или иной проблемы, которую нужно будет ещё подстроить под нужды вашей программы.
//:
//: ### Паттерны часто путают с алгоритмами, ведь оба понятия описывают типовые решения каких-то известных проблем. Но если алгоритм — это чёткий набор действий, то паттерн — это высокоуровневое описание решения, реализация которого может отличаться в двух разных программах.
//:
//: ### Если привести аналогии, то алгоритм — это кулинарный рецепт с чёткими шагами, а паттерн — инженерный чертёж, на котором нарисовано решение, но не конкретные шаги его реализации.
//:
//: ## Паттерны делятся на:
//: * [порождающие](@next)
//: * [структурные](StructuralPatterns)
//: * [поведенческие](BehavioralPatterns)
<file_sep>/GoFPatterns.playground/Pages/CreationalPatterns.xcplaygroundpage/Contents.swift
//: [к содержанию](Intro)
//:
//: [к структурным паттернам](StructuralPatterns)
//:
//: [к поведенеческим паттернам](BehavioralPatterns)
import Foundation
//: # _Порождающие паттерны_
//:
//: ## _Factory Method_
//: ### Фабричный метод — это порождающий паттерн проектирования, который определяет общий интерфейс для создания объектов в суперклассе, позволяя подклассам изменять тип создаваемых объектов.
//: [Более подробно](https://refactoring.guru/ru/design-patterns/factory-method)
protocol Drivable{
func Drive()
}
class Car: Drivable{
func Drive(){
print("Drive car!")
}
}
class Track: Drivable{
func Drive(){
print("Drive track!")
}
}
class Bus: Drivable{
func Drive(){
print("Drive bus!")
}
}
enum Vehicle{
case BMWx5
case KAMAZ
case MercedesTourismo
}
enum VehicleFactory{
static func drive(for car: Vehicle) -> Drivable {
switch car{
case .BMWx5:
return Car()
case .KAMAZ:
return Track()
case .MercedesTourismo:
return Bus()
}
}
}
(VehicleFactory.drive(for: .BMWx5) as Drivable).Drive()
(VehicleFactory.drive(for: .KAMAZ) as Drivable).Drive()
(VehicleFactory.drive(for: .MercedesTourismo) as Drivable).Drive()
//: ## _Abstract Factory_
//: ### Абстрактная фабрика — это порождающий паттерн проектирования, который позволяет создавать семейства связанных объектов, не привязываясь к конкретным классам создаваемых объектов.
//: [Более подробно](https://refactoring.guru/ru/design-patterns/abstract-factory)
protocol VehicleDrivable{
func Drive()
}
class BMWCars: VehicleDrivable{
func Drive(){
print("BMW driving")
}
}
class MercedesCars: VehicleDrivable{
func Drive(){
print("Mercedes driving")
}
}
protocol CarAbstractFactory{
func CreateCar() -> VehicleDrivable
}
final class BMWFactory: CarAbstractFactory{
func CreateCar() -> VehicleDrivable{
return BMWCars()
}
}
final class MercedesFactory: CarAbstractFactory{
func CreateCar() -> VehicleDrivable{
return MercedesCars()
}
}
enum CarsFactoryType: CarAbstractFactory{
case bmw
case mercedes
func CreateCar() -> VehicleDrivable{
switch self{
case .bmw:
return BMWFactory().CreateCar()
case .mercedes:
return MercedesFactory().CreateCar()
}
}
}
CarsFactoryType.bmw.CreateCar().Drive()
CarsFactoryType.mercedes.CreateCar().Drive()
//: ## _Prototype_
//: ### Прототип — это порождающий паттерн проектирования, который позволяет копировать объекты, не вдаваясь в подробности их реализации.
//: [Более подробно](https://refactoring.guru/ru/design-patterns/prototype)
protocol Prototype{
associatedtype Object
func clone() -> Object
}
struct Plane: Prototype{
var name: String
let wingspan: Double
init(name: String, wingspan: Double){
self.name = name
self.wingspan = wingspan
}
func clone() -> Plane {
return Plane(name: self.name, wingspan: self.wingspan)
}
}
let il96_protype = Plane(name: "IL-96", wingspan: 60)
var il96_400 = il96_protype.clone()
il96_400.name += "-400"
print("\(il96_400)")
var il96_300 = il96_protype.clone()
il96_300.name += "-300"
print("\(il96_300)")
var il96_MD = il96_protype.clone()
il96_MD.name += "MD"
print("\(il96_MD)")
//: ## _Builder_
//: ### Строитель — это порождающий паттерн проектирования, который позволяет создавать сложные объекты пошагово. Строитель даёт возможность использовать один и тот же код строительства для получения разных представлений объектов.
//: [Более подробно](https://refactoring.guru/ru/design-patterns/builder)
final class WallBuiler{
var walls: String?
typealias wallBuilderClosure = (WallBuiler) -> Void
init (wallBuildClosure: (WallBuiler) -> Void){
wallBuildClosure(self)
}
}
final class WindowsBuiler{
var windows: String?
typealias windowsBuilderClosure = (WindowsBuiler) -> Void
init (windowsBuildClosure: (WindowsBuiler) -> Void){
windowsBuildClosure(self)
}
}
class HouseBuilder{
var walls: String?
var windows: String?
//опциональный иницилизатор
init?(wallBuilder: WallBuiler?, windowsBuiler: WindowsBuiler?){
if let walls = wallBuilder?.walls{
self.walls = walls
}
if let windows = windowsBuiler?.windows{
self.windows = windows
}
}
}
let wallbuilder = WallBuiler{
wallBldr in wallBldr.walls = "Build walls"
}
let windowsBilder = WindowsBuiler{
windowsBldr in windowsBldr.windows = "Build windows"
}
var house = HouseBuilder(wallBuilder: wallbuilder, windowsBuiler: windowsBilder)
print("Walls: \(String(describing: house?.walls)), windows: \(String(describing: house?.windows))")
//: ## _Singletone_
//: ### Одиночка — это порождающий паттерн проектирования, который гарантирует, что у класса есть только один экземпляр, и предоставляет к нему глобальную точку доступа.
//: * Одиночка решает сразу две проблемы, нарушая принцип единственной ответственности класса. Гарантирует наличие единственного экземпляра класса. Чаще всего это полезно для доступа к какому-то общему ресурсу, например, базе данных.
//: * Предоставляет глобальную точку доступа. Это не просто глобальная переменная, через которую можно достучаться к определённому объекту. Глобальные переменные не защищены от записи, поэтому любой код может подменять их значения без вашего ведома.
//: Правительство государства — хороший пример одиночки. В государстве может быть только одно официальное правительство. Вне зависимости от того, кто конкретно заседает в правительстве, оно имеет глобальную точку доступа «Правительство страны N».
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/singleton)
final class Singletone{
static let shared = Singletone()
private init(){
//приватная инициализация для уверенности, что будет создан один инстанс класса
}
}
let instance = Singletone.shared
//: [к содержанию](Intro)
//:
//: [к структурным паттернам](StructuralPatterns)
//:
//: [к поведенеческим паттернам](BehavioralPatterns)
//:
<file_sep>/GoFPatterns.playground/Pages/BehavioralPatterns.xcplaygroundpage/Contents.swift
//: [к содержанию](Intro)
//:
//: [к порождающим паттернам](CreationalPatterns)
//:
//: [к структурным паттернам](StructuralPatterns)
import Foundation
//: # _Поведенческие паттерны_
//:
//: ## _Command_
//: ### Команда — это поведенческий паттерн проектирования, который превращает запросы в объекты, позволяя передавать их как аргументы при вызове методов, ставить запросы в очередь, логировать их, а также поддерживать отмену операций.
//:Участники:
//: * Command: интерфейс, представляющий команду. Обычно определяет метод Execute() для выполнения действия, а также нередко включает метод Undo(), реализация которого должна заключаться в отмене действия команды
//: * ConcreteCommand: конкретная реализация команды, реализует метод Execute(), в котором вызывается определенный метод, определенный в классе Receiver
//: * Receiver: получатель команды. Определяет действия, которые должны выполняться в результате запроса.
//: * Invoker: инициатор команды - вызывает команду для выполнения определенного запроса
//: * Client: клиент - создает команду и устанавливает ее получателя с помощью метода SetCommand()
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/command) и [тут](https://metanit.com/sharp/patterns/3.3.php)
///Command
protocol Command{
func Execute()
func Undo()
}
///Receiver
struct Microwave{
func startCooking(){
print("Подогреваем еду")
}
func stopCooking(){
print("Еда подогрета!")
}
func cancelCooking(){
print("Отменить подогрев!")
}
}
///ConcreteCommand
struct MicrowaveCommand : Command{
let microwave: Microwave
func Execute() {
microwave.startCooking()
microwave.stopCooking()
}
func Undo() {
microwave.cancelCooking()
}
init(microwave: Microwave){
self.microwave = microwave
}
}
let microwave = Microwave()
let command = MicrowaveCommand(microwave: microwave)
command.Execute()
command.Undo()
//: ## _Strategy_
//: ### Стратегия — это поведенческий паттерн проектирования, который определяет семейство схожих алгоритмов и помещает каждый из них в собственный класс, после чего алгоритмы можно взаимозаменять прямо во время исполнения программы.
//:Участники:
//: * Интерфейс Strategy: бщий интерфейс для всех реализующих его алгоритмов.
//: * Классы ConcreteStrategy1 и ConcreteStrategy, которые реализуют интерфейс Strategy, предоставляя свою версию метода Algorithm(). Подобных классов-реализаций может быть множество.
//: * Класс Context хранит ссылку на объект Strategy и связан с интерфейсом Strategy отношением агрегации.
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/strategy) и [тут](https://metanit.com/sharp/patterns/3.1.php)
///Strategy
protocol Movable
{
func move()
}
///ConcreteStrategy1
struct PetrolMove : Movable{
func move(){
print("Перемещение на бензине")
}
}
///ConcreteStrategy2
struct ElectricMove : Movable{
func move(){
print("Перемещение на электричестве")
}
}
///Context
struct Car{
let passengers: Int // кол-во пассажиров
let model: String // модель автомобиля
var strategy: Movable
init(passengers: Int, model: String , strategy: Movable ){
self.passengers = passengers
self.model = model
self.strategy = strategy
}
func move(){
strategy.move()
}
}
var auto = Car(passengers: 4, model: "Volvo", strategy: PetrolMove())
auto.move()
auto.strategy = ElectricMove()
auto.move();
//: ## _Mediator_
//: ### Медиатор — это поведенческий паттерн проектирования, который позволяет уменьшить связанность (reduce coupling) множества классов между собой, благодаря перемещению этих связей в один класс-посредник.
//:Когда используется паттерн Посредник?
//: * Когда имеется множество взаимосвязаных объектов, связи между которыми сложны и запутаны.
//: * Когда необходимо повторно использовать объект, однако повторное использование затруднено в силу сильных связей с другими объектами.
//:
//:Участники:
//: * Mediator: представляет интерфейс для взаимодействия с объектами Colleague
//: * Colleague: представляет интерфейс для взаимодействия с объектом Mediator
//: * ConcreteColleague1 и ConcreteColleague2: конкретные классы коллег, которые обмениваются друг с другом через объект Mediator
//: * ConcreteMediator: конкретный посредник, реализующий интерфейс типа Mediator
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/mediator) и [тут](https://metanit.com/sharp/patterns/3.9.php)
///Mediator
protocol Mediator{
func send(message: String, from colleague: Colleague)
}
protocol Colleague{
var mediator: Mediator { get set }
func send(message: String)
func notify(message: String);
}
extension Colleague{
func send(message: String){
mediator.send(message: message, from: self)
}
}
// класс заказчика
struct CustomerColleague : Colleague{
var mediator: Mediator
func notify(message: String){
print("Сообщение заказчику: \(message)")
}
}
// класс программиста
struct ProgrammerColleague : Colleague{
var mediator: Mediator
func notify(message: String){
print("Сообщение программисту: \(message)")
}
}
// класс тестера
struct TesterColleague : Colleague{
var mediator: Mediator
func notify(message: String){
print("Сообщение тестировщику: \(message)")
}
}
class ManagerMediator : Mediator{
var customer: Colleague?
var programmer: Colleague?
var tester: Colleague?
func send(message: String, from colleague: Colleague) {
// если отправитель - заказчик, значит есть новый заказ
// отправляем сообщение программисту - выполнить заказ
if (colleague is CustomerColleague){
programmer?.notify(message: message)
}
// если отправитель - программист, то можно приступать к тестированию
// отправляем сообщение тестеру
else if (colleague is ProgrammerColleague){
tester?.notify(message: message)
}
// если отправитель - тест, значит продукт готов
// отправляем сообщение заказчику
else if (colleague is TesterColleague){
customer?.notify(message: message)
}
}
}
var mediator = ManagerMediator()
var customer = CustomerColleague(mediator: mediator)
var programmer = ProgrammerColleague(mediator: mediator)
var tester = TesterColleague(mediator: mediator)
mediator.customer = customer
mediator.programmer = programmer
mediator.tester = tester
customer.send(message: "Есть заказ, надо сделать программу")
programmer.send(message: "Программа готова, надо протестировать")
tester.send(message: "Программа протестирована и готова к продаже")
//: ## _Template_
//: ### Шаблонный метод — это поведенческий паттерн проектирования, который определяет скелет алгоритма, перекладывая ответственность за некоторые его шаги на подклассы. Паттерн позволяет подклассам переопределять шаги алгоритма, не меняя его общей структуры.
//:Когда использовать шаблонный метод?
//: * Когда планируется, что в будущем подклассы должны будут переопределять различные этапы алгоритма без изменения его структуры
//: * Когда в классах, реализующим схожий алгоритм, происходит дублирование кода. Вынесение общего кода в шаблонный метод уменьшит его дублирование в подклассах.
//:
//:Участники:
//: * AbstractClass: определяет шаблонный метод TemplateMethod(), который реализует алгоритм. Алгоритм может состоять из последовательности вызовов других методов, часть из которых может быть абстрактными и должны быть переопределены в классах-наследниках. При этом сам метод TemplateMethod(), представляющий структуру алгоритма, переопределяться не должен.
//: * ConcreteClass: подкласс, который может переопределять различные методы родительского класса.
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/template-method) и [тут](https://metanit.com/sharp/patterns/3.4.php)
///AbstractClass
protocol Education{
func Learn()
func Enter();
func Study();
func PassExams()
func GetDocument();
}
extension Education{
func PassExams(){
print("Сдаем выпуксные экзамены!")
}
func Learn(){
Enter();
Study();
PassExams();
GetDocument();
}
}
///ConcreteClass
class School : Education
{
func Enter(){
print("Идем в первый класс")
}
func Study(){
print("Посещаем уроки, делаем домашние задания")
}
func GetDocument(){
print("Получаем аттестат о среднем образовании")
}
}
let school = School()
school.Learn()
//: ## _Memento_
//: ### Снимок — это поведенческий паттерн проектирования, который позволяет сохранять и восстанавливать прошлые состояния объектов, не раскрывая подробностей их реализации.
//:Когда использовать Memento?
//: * Когда нужно сохранить состояние объекта для возможного последующего восстановления.
//: * Когда сохранение состояния должно проходить без нарушения принципа инкапсуляции.
//:
//:Участники:
//: * Memento: хранитель, который сохраняет состояние объекта Originator и предоставляет полный доступ только этому объекту Originator
//: * Originator: создает объект хранителя для сохранения своего состояния
//: * Caretaker: выполняет только функцию хранения объекта Memento, в то же время у него нет полного доступа к хранителю и никаких других операций над хранителем, кроме собственно сохранения, он не производит
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/memento) и [тут](https://metanit.com/sharp/patterns/3.10.php)
// Memento
class HeroMemento{
var patrons: Int
var lives: Int
init (_ patrons: Int, _ lives: Int)
{
self.patrons = patrons
self.lives = lives
}
}
// Originator
class Hero{
var patrons = 10 // кол-во патронов
var lives = 5 // кол-во жизней
func Shoot(){
if (patrons > 0)
{
patrons -= 1;
print("Производим выстрел. Осталось \(patrons) патронов")
}
else { print("Патронов больше нет") }
}
// сохранение состояния
func SaveState()-> HeroMemento{
print("Сохранение игры. Параметры: \(patrons) патронов, \(lives) жизней")
return HeroMemento(patrons, lives)
}
// восстановление состояния
func RestoreState(memento: HeroMemento){
self.patrons = memento.patrons;
self.lives = memento.lives;
print("Восстановление игры. Параметры: \(patrons) патронов, \(lives) жизней")
}
}
// Caretaker
class GameHistory{
var History = [HeroMemento]()
}
var hero = Hero()
hero.Shoot() // делаем выстрел, осталось 9 патронов
var game = GameHistory()
game.History.append(hero.SaveState()) // сохраняем игру
hero.Shoot() //делаем выстрел, осталось 8 патронов
hero.RestoreState(memento: game.History.last!)
hero.Shoot(); //делаем выстрел, осталось 8 патронов
//: ## _Observer (Publisher-Subscriber)_
//: ### Наблюдатель — это поведенческий паттерн проектирования, который создаёт механизм подписки, позволяющий одним объектам следить и реагировать на события, происходящие в других объектах.
//:Когда использовать Наблюдатель?
//: * Когда система состоит из множества классов, объекты которых должны находиться в согласованных состояниях
//: * Когда общая схема взаимодействия объектов предполагает две стороны: одна рассылает сообщения и является главным, другая получает сообщения и реагирует на них. Отделение логики обеих сторон позволяет их рассматривать независимо и использовать отдельно друга от друга.
//: * Когда существует один объект, рассылающий сообщения, и множество подписчиков, которые получают сообщения. При этом точное число подписчиков заранее неизвестно и процессе работы программы может изменяться.
//:
//:Участники:
//: * Observable: представляет наблюдаемый объект. Определяет три метода: AddObserver() (для добавления наблюдателя), RemoveObserver() (удаление набюдателя) и NotifyObservers() (уведомление наблюдателей)
//: * ConcreteObservable: конкретная реализация интерфейса Observable. Определяет коллекцию объектов наблюдателей.
//: * Observer: представляет наблюдателя, который подписывается на все уведомления наблюдаемого объекта. Определяет метод Update(), который вызывается наблюдаемым объектом для уведомления наблюдателя.
//: * ConcreteObserver: конкретная реализация интерфейса IObserver.
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/observer) и [тут](https://metanit.com/sharp/patterns/3.2.php)
///Observer
protocol Subscriber{
func Update(stockInfo: StockInfo)
func isEqualTo(_ other: Subscriber) -> Bool
}
extension Subscriber where Self : Equatable{
func isEqualTo(_ other: Subscriber) -> Bool {
guard let otherSubscriber = other as? Self else { return false }
return self == otherSubscriber
}
}
///Observable
protocol Publisher{
var subscribers: [Subscriber] { get set }
func RegisterObserver(subscriber: Subscriber)
func RemoveObserver(subscriber: Subscriber)
func NotifyObservers()
}
// информация о торгах
class StockInfo{
var USD: Double = 0
var Euro: Double = 0
}
class Broker : Subscriber, Equatable{
func Update(stockInfo: StockInfo) {
if(stockInfo.USD > 61){
print("Брокер \(self.name) продает доллары; Курс доллара: \(stockInfo.USD)")
}
else{
print("Брокер \(self.name) покупает доллары; Курс доллара: \(stockInfo.USD)")
}
}
static func == (lhs: Broker, rhs: Broker) -> Bool {
return lhs.id == rhs.id
}
let name: String
let id = UUID()
var stock: Stock
init(name: String, stock: Stock)
{
self.name = name
self.stock = stock
stock.RegisterObserver(subscriber: self)
}
func StopTrade(){
self.stock.RemoveObserver(subscriber: self)
}
}
class Bank : Subscriber, Equatable{
static func == (lhs: Bank, rhs: Bank) -> Bool {
return lhs.id == rhs.id
}
let name: String
let id = UUID()
var stock: Stock
init(name: String, stock: Stock){
self.name = name
self.stock = stock
stock.RegisterObserver(subscriber: self)
}
func Update(stockInfo: StockInfo) {
if (stockInfo.Euro > 76){
print("Банк \(self.name) продает евро; Курс евро: \(stockInfo.Euro)")
}
else{
print("Банк \(self.name) покупает евро; Курс евро: \(stockInfo.Euro)")
}
}
}
//биржа
final class Stock: Publisher{
var subscribers: [Subscriber]
//акции
var sInfo: StockInfo
func RegisterObserver(subscriber: Subscriber) {
self.subscribers.append(subscriber)
}
func RemoveObserver(subscriber: Subscriber){
if let index = self.subscribers.firstIndex(where: {$0.isEqualTo(subscriber) }){
self.subscribers.remove(at: index)
}
}
func NotifyObservers() {
for subscriber in self.subscribers{
subscriber.Update(stockInfo: sInfo)
}
}
func Trade(){
sInfo.USD = Double.random(in: 60.0 ..< 70.0)
sInfo.Euro = Double.random(in: 70.0 ..< 80.0)
self.NotifyObservers()
}
init(){
self.subscribers = [Subscriber]()
self.sInfo = StockInfo()
}
}
var stock = Stock()
var bank = Bank(name: "ЮнитБанк", stock: stock)
var broker = Broker(name: "<NAME>", stock: stock)
// имитация торгов
stock.Trade()
// брокер прекращает наблюдать за торгами
broker.StopTrade()
// имитация торгов
stock.Trade()
stock.Trade()
//: ## _Iterator_
//: ### Итератор — это поведенческий паттерн проектирования, который даёт возможность последовательно обходить элементы составных объектов, не раскрывая их внутреннего представления.
//:Когда использовать итератор?
//: * Когда необходимо осуществить обход объекта без раскрытия его внутренней структуры
//: * Когда имеется набор составных объектов, и надо обеспечить единый интерфейс для их перебора
//: * Когда необходимо предоставить несколько альтернативных вариантов перебора одного и того же объекта
//:
//:Участники:
//: * Iterator: определяет интерфейс для обхода составных объектов
//: * Aggregate: определяет интерфейс для создания объекта-итератора
//: * ConcreteIterator: конкретная реализация итератора для обхода объекта Aggregate. Для фиксации индекса текущего перебираемого элемента использует целочисленную переменную _current
//: * ConcreteAggregate: конкретная реализация Aggregate. Хранит элементы, которые надо будет перебирать
//: * Client: использует объект Aggregate и итератор для его обхода
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/iterator) и [тут](https://metanit.com/sharp/patterns/3.5.php)
struct SuffixIterator : IteratorProtocol{
//state:
let string: String
var last : String.Index
var offset: String.Index
init(string: String) {
self.string = string
self.last = string.endIndex
self.offset = string.startIndex
}
mutating func next() -> Substring?{
guard offset < last else { return nil }
let sub: Substring = string[offset..<last]
string.formIndex(after: &offset)
return sub
}
}
struct SuffixSequence: Sequence {
let string: String
func makeIterator() -> SuffixIterator{
return SuffixIterator(string: string)
}
}
for suffix in SuffixSequence(string: "Pattern Iterator"){
print(suffix)
}
//: ## _State_
//: ### Состояние — это поведенческий паттерн проектирования, который позволяет объектам менять поведение в зависимости от своего состояния. Извне создаётся впечатление, что изменился класс объекта.
//:Когда использовать паттерн?
//: * Когда поведение объекта должно зависеть от его состояния и может изменяться динамически во время выполнения
//: * Когда в коде методов объекта используются многочисленные условные конструкции, выбор которых зависит от текущего состояния объекта
//:
//:Участники:
//: * State: определяет интерфейс состояния
//: * Классы StateA и StateB - конкретные реализации состояний
//: * Context: представляет объект, поведение которого должно динамически изменяться в соответствии с состоянием. Выполнение же конкретных действий делегируется объекту состояния
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/state) и [тут](https://metanit.com/sharp/patterns/3.6.php)
///State:
protocol WaterState{
func Heat()-> WaterState
func Frost()-> WaterState
}
///Context:
class Water{
var state: WaterState
init (state: WaterState){
self.state = state
}
func Heat() {
self.state = state.Heat()
}
func Frost() {
self.state = state.Frost()
}
}
///StateA:
class SolidWaterState : WaterState{
var water: Water?
func Heat() -> WaterState{
print("Превращаем лед в жидкость")
return LiquidWaterState()
}
func Frost() -> WaterState{
print("Продолжаем заморозку льда")
return SolidWaterState()
}
}
///StateB:
class LiquidWaterState : WaterState{
func Heat() -> WaterState{
print("Превращаем жидкость в пар")
return GasWaterState()
}
func Frost() -> WaterState{
print("Превращаем жидкость в лед")
return SolidWaterState()
}
}
///StateC:
class GasWaterState : WaterState{
func Heat() -> WaterState{
print("Повышаем температуру водяного пара")
return GasWaterState()
}
func Frost() -> WaterState {
print("Превращаем водяной пар в жидкость")
return LiquidWaterState()
}
}
var water = Water(state: LiquidWaterState())
water.Heat()
water.Heat()
water.Frost()
water.Frost()
water.Heat()
//: ## _Chain of responsibility_
//: ### Цепочка обязанностей — это поведенческий паттерн проектирования, который позволяет передавать запросы последовательно по цепочке обработчиков. Каждый последующий обработчик решает, может ли он обработать запрос сам и стоит ли передавать запрос дальше по цепи.
//:Когда использовать паттерн?
//: * Когда имеется более одного объекта, который может обработать определенный запрос
//: * Когда надо передать запрос на выполнение одному из нескольких объект, точно не определяя, какому именно объекту
//: * Когда набор объектов задается динамически
//:
//:Участники:
//: * Handler: определяет интерфейс для обработки запроса. Также может определять ссылку на следующий обработчик запроса
//: * ConcreteHandler1 и ConcreteHandler2: конкретные обработчики, которые реализуют функционал для обработки запроса. При невозможности обработки и наличия ссылки на следующий обработчик, передают запрос этому обработчику
//: * Client: отправляет запрос объекту Handler
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/chain-of-responsibility) и [тут](https://metanit.com/sharp/patterns/3.7.php)
class Receiver{
// банковские переводы
let BankTransfer: Bool?
// денежные переводы - WesternUnion, Unistream
let MoneyTransfer: Bool?
// перевод через PayPal
let PayPalTransfer: Bool?
init(bt : Bool, mt: Bool, ppt: Bool)
{
BankTransfer = bt
MoneyTransfer = mt
PayPalTransfer = ppt
}
}
protocol PaymentHandler{
var successor: PaymentHandler? { get }
func Handle(receiver: Receiver)
}
final class BankPaymentHandler : PaymentHandler
{
var successor: PaymentHandler?
func Handle(receiver: Receiver){
if (receiver.BankTransfer == true){
print("Выполняем банковский перевод")
} else {self.successor?.Handle(receiver: receiver)}
}
}
final class PayPalPaymentHandler : PaymentHandler{
var successor: PaymentHandler?
func Handle(receiver: Receiver){
if (receiver.PayPalTransfer == true){
print("Выполняем перевод через PayPal")
} else {self.successor?.Handle(receiver: receiver)}
}
}
// переводы с помощью системы денежных переводов
final class MoneyPaymentHandler : PaymentHandler
{
var successor: PaymentHandler?
func Handle(receiver: Receiver){
if (receiver.MoneyTransfer == true){
print("Выполняем перевод через системы денежных переводов")
}
else {self.successor?.Handle(receiver: receiver)}
}
}
var bankPaymentHandler = BankPaymentHandler()
var moneyPaymentHadler = MoneyPaymentHandler()
var paypalPaymentHandler = PayPalPaymentHandler()
bankPaymentHandler.successor = paypalPaymentHandler
paypalPaymentHandler.successor = moneyPaymentHadler
let receiver = Receiver(bt: false, mt: true, ppt: true)
bankPaymentHandler.Handle(receiver: receiver)
//: ## _Visitor_
//: ### Посетитель — это поведенческий паттерн проектирования, который позволяет добавлять в программу новые операции, не изменяя классы объектов, над которыми эти операции могут выполняться.
//:Когда использовать паттерн?
//: * Когда имеется много объектов разнородных классов с разными интерфейсами, и требуется выполнить ряд операций над каждым из этих объектов
//: * Когда классам необходимо добавить одинаковый набор операций без изменения этих классов
//: * Когда часто добавляются новые операции к классам, при этом общая структура классов стабильна и практически не изменяется
//:
//:Участники:
//: * Visitor: интерфейс посетителя, который определяет метод Visit() для каждого объекта Element
//: * ConcreteVisitor1 / ConcreteVisitor2: конкретные классы посетителей, реализуют интерфейс, определенный в Visitor.
//: * Element: определяет метод Accept(), в котором в качестве параметра принимается объект Visitor
//: * ElementA / ElementB: конкретные элементы, которые реализуют метод Accept()
//: *ObjectStructure: некоторая структура, которая хранит объекты Element и предоставляет к ним доступ. Это могут быть и простые списки, и сложные составные структуры в виде деревьев
//:
//: [Более подробно](https://refactoring.guru/ru/design-patterns/visitor) и [тут](https://metanit.com/sharp/patterns/3.11.php)
///Visitor
protocol Visitor{
func VisitPersonAcc(person: Person)
func VisitCompanyAc(company: Company)
}
///ConcreteVisitor1
// сериализатор в HTML
class HtmlVisitor : Visitor
{
func VisitPersonAcc(person: Person) {
var result = "<table><tr><td>Свойство<td><td>Значение</td></tr>"
result += "<tr><td>Name<td><td>\(String(describing: person.name))</td></tr>"
result += "<tr><td>Number<td><td>\(String(describing: person.number))</td></tr></table>"
print(result)
}
func VisitCompanyAc(company: Company) {
var result = "<table><tr><td>Свойство<td><td>Значение</td></tr>"
result += "<tr><td>Name<td><td>\(String(describing: company.name))</td></tr>"
result += "<tr><td>RegNumber<td><td>\(String(describing: company.regNumber))</td></tr>"
result += "<tr><td>Number<td><td>\(String(describing: company.number))</td></tr></table>"
print(result)
}
}
///ConcreteVisitor2
// сериализатор в XML
class XmlVisitor : Visitor
{
func VisitPersonAcc(person: Person) {
let result = "<Person><Name>\(String(describing: person.name))</Name><Number>\(String(describing: person.number))</Number><Person>"
print(result)
}
func VisitCompanyAc(company: Company) {
let result = "<Company><Name>\(String(describing: company.name))</Name><RegNumber>\(String(describing: company.regNumber))</RegNumber><Number>\(String(describing: company.number))</Number><Company>"
print(result)
}
}
class BankTrust{
var accounts = [Account]()
func Add(acc: Account){
accounts.append(acc)
}
func Accept(visitor: Visitor){
for acc in self.accounts {
acc.Accept(visitor: visitor)
}
}
}
protocol Account{
func Accept(visitor: Visitor)
}
class Person : Account
{
var name: String
var number: String
func Accept(visitor: Visitor){
visitor.VisitPersonAcc(person: self)
}
init(_ name: String, _ number: String){
self.name = name
self.number = number
}
}
class Company : Account
{
var name: String
var regNumber: String
var number: String
func Accept(visitor: Visitor){
visitor.VisitCompanyAc(company: self)
}
init(_ name: String,_ regNumber: String, _ number: String){
self.name = name
self.regNumber = regNumber
self.number = number
}
}
var structure = BankTrust()
structure.Add(acc: Person("<NAME>", "82184931"))
structure.Add(acc: Company("Apple","ewuir32141324","3424131445"))
structure.Accept(visitor: HtmlVisitor())
structure.Accept(visitor: XmlVisitor())
//: [к содержанию](Intro)
//:
//: [к порождающим паттернам](CreationalPatterns)
//:
//: [к структурным паттернам](StructuralPatterns)
| e337323961efb948ec9a66b0f5c5d4e03da96eac | [
"Markdown",
"Swift"
] | 5 | Markdown | c-villain/GoFPatterns | 7840be5b68d773f184ae621f0095ca541795c32e | 416eb8f0829d1360454f579eb0b96c4b333f7a8b |
refs/heads/master | <repo_name>miguel2014/Componentes<file_sep>/diapositivas/PersonaHIjosModel.java
package diapositivas;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class PersonaHIjosModel implements TreeModel {
PersonaHijosde raiz;
/**
* @param raiz
*/
public PersonaHIjosModel(PersonaHijosde raiz) {
this.raiz = raiz;
}
@Override
public Object getRoot() {
// TODO Auto-generated method stub
return raiz;
}
@Override
public Object getChild(Object parent, int index) {
// TODO Auto-generated method stub
PersonaHijosde nodo=(PersonaHijosde)parent;
return nodo.getHijo(index);
}
@Override
public int getChildCount(Object parent) {
// TODO Auto-generated method stub
return ((PersonaHijosde)parent).numeroHijos();
}
@Override
public boolean isLeaf(Object node) {
// TODO Auto-generated method stub
return ((PersonaHijosde)node).tieneHijos();
}
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
// TODO Auto-generated method stub
}
@Override
public int getIndexOfChild(Object parent, Object child) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void addTreeModelListener(TreeModelListener l) {
// TODO Auto-generated method stub
}
@Override
public void removeTreeModelListener(TreeModelListener l) {
// TODO Auto-generated method stub
}
}
<file_sep>/diapositivas/JTreeDemo.java
package diapositivas;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class JTreeDemo {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTreeDemo window = new JTreeDemo();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JTreeDemo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode datosjugadores=crearArbol();
JTree treeJugadores=new JTree(datosjugadores);
JScrollPane scroll=new JScrollPane(treeJugadores);
frame.add(scroll,BorderLayout.CENTER);
}
private DefaultMutableTreeNode crearArbol(){
DefaultMutableTreeNode raiz=new DefaultMutableTreeNode("Equipos");
DefaultMutableTreeNode madrid=new DefaultMutableTreeNode("Juve");
DefaultMutableTreeNode jaen=new DefaultMutableTreeNode("Jaen");
DefaultMutableTreeNode barsa=new DefaultMutableTreeNode("Barsa");
raiz.add(barsa);raiz.add(madrid);raiz.add(jaen);
DefaultMutableTreeNode jaenj1=new DefaultMutableTreeNode("Montero");
DefaultMutableTreeNode jaenj2=new DefaultMutableTreeNode("Picao");
jaen.add(jaenj1);jaen.add(jaenj2);
DefaultMutableTreeNode madridj1=new DefaultMutableTreeNode("Enano");
madrid.add(madridj1);
return raiz;
}
}
<file_sep>/diapositivas/PersonaHijosde.java
package diapositivas;
import java.util.ArrayList;
public class PersonaHijosde {
private String nombre;
private String apellido1;
private String apellido2;
@SuppressWarnings("unused")
private PersonaHijosde padre;
private ArrayList<PersonaHijosde> hijos;
/**
* @param nombre
* @param apellido1
* @param apellido2
* @param padre
* @param hijos
*/
public PersonaHijosde(String nombre, String apellido1, String apellido2) {
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.padre = null;
this.hijos = new ArrayList<PersonaHijosde>();
}
public void setPadre(PersonaHijosde padre) {
this.padre = padre;
}
public void addHijo(PersonaHijosde hijo){
hijos.add(hijo);
hijo.setPadre(this);
}
public PersonaHijosde getHijo(int i){
return hijos.get(i);
}
public int numeroHijos(){
return hijos.size();
}
public boolean tieneHijos(){
return !hijos.isEmpty();
}
@Override
public String toString() {
return "PersonaHijosde [nombre=" + nombre + ", apellido1=" + apellido1
+ ", apellido2=" + apellido2 + "]";
}
public void pintaArbol(){
if (this.tieneHijos()) {
System.out.println(this);//Si no tiene hijos
} else {
System.out.println(this);
for (PersonaHijosde personaHijosde : hijos) {
personaHijosde.pintaArbol();
}
}
}
}
| c27df1b14c4937c3ad1d4e96a9d88efcd798a7fd | [
"Java"
] | 3 | Java | miguel2014/Componentes | 59f41f738aa5a7603ffc2c838f6b8c6fc39cbca3 | 73a0f448e6dd071d535c27196fdad64d2a94339d |
refs/heads/master | <repo_name>ZanSaito/InDevelopment<file_sep>/In Development Project/Assets/Scripts/Stats/ResourceComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ResourceComponent
{
//----Health-----
protected float m_MaxAmount;
protected float m_CurrentResource;
// setting current Resource to starting Resource
//TODO: Take over HP from last Scene when new level loads
/// <summary>
/// reduces Resource by amount
/// </summary>
/// <param name="damage"></param>
public void Reduce(float damage)
{
var newHealth = m_CurrentResource - damage;
m_CurrentResource = Mathf.Clamp(newHealth, 0f, m_MaxAmount);
}
/// <summary>
/// increases Health by amount
/// </summary>
/// <param name="damage"></param>
public void Increase(float amount)
{
var newResource = m_CurrentResource + amount;
m_CurrentResource = Mathf.Clamp(newResource, 0f, m_MaxAmount);
}
/// <summary>
/// gets remaining Resource in percent between 1.0 and 0.0
/// </summary>
/// <returns></returns>
public float getPercentage()
{
return m_CurrentResource / m_MaxAmount;
}
}
<file_sep>/In Development Project/Assets/Scripts/Entity/LivingEntity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Combat;
public class LivingEntity : MonoBehaviour
{
[HideInInspector] public Animator animator;
Stats stats;
private void Start()
{
stats = GetComponent<Stats>();
PostStart();
}
public virtual void PostStart()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Weapon")
{
Weapon weapon = other.GetComponent<Weapon>();
handleHitByWeapon(weapon);
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.tag == "Companion" || collision.collider.tag == "Player")
{
Physics.IgnoreCollision(collision.collider, GetComponent<Collider>());
}
}
public void takeDamage(float amount)
{
if(stats)
{
ResourceComponent health = stats.Get(StatType.Health);
if(health != null)
{
health.Reduce(amount);
}
}
}
// Handled in super class
public virtual void handleHitByWeapon(Weapon weapon)
{
}
public virtual Transform findWeaponOrigin()
{
return transform;
}
public virtual Transform findBackOrigin()
{
return transform;
}
public virtual void basicAttackDone()
{
}
public virtual void basicAttackStarted()
{
}
}
<file_sep>/In Development Project/Assets/Scripts/Stats/Editor/StatsEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[System.Serializable]
[CanEditMultipleObjects]
[CustomEditor(typeof(Stats))]
public class StatsEditor : Editor
{
//------HEALTH-----
SerializedProperty m_HealthEnabled;
SerializedProperty m_MaxHP;
SerializedProperty m_HealthRegen;
bool showHealthStats = false;
//------MANA-----
SerializedProperty m_ManaEnabled;
SerializedProperty m_MaxMana;
SerializedProperty m_ManaRegen;
bool showManaStats = false;
//----EXPERIENCE----
private void OnEnable()
{
m_HealthEnabled = serializedObject.FindProperty("m_HealthEnabled");
m_MaxHP = serializedObject.FindProperty("m_MaxHP");
m_HealthRegen = serializedObject.FindProperty("m_HealthRegen");
m_ManaEnabled = serializedObject.FindProperty("m_ManaEnabled");
m_MaxMana = serializedObject.FindProperty("m_MaxMana");
m_ManaRegen = serializedObject.FindProperty("m_ManaRegen");
}
public override void OnInspectorGUI()
{
Stats stats = target as Stats;
serializedObject.Update();
//-----HEALTH----
m_HealthEnabled.boolValue = EditorGUILayout.BeginToggleGroup("Health", m_HealthEnabled.boolValue);
showHealthStats = EditorGUILayout.BeginFoldoutHeaderGroup(showHealthStats, "Health Stats");
if (showHealthStats && m_HealthEnabled.boolValue)
{
EditorGUI.indentLevel++;
m_MaxHP.intValue = EditorGUILayout.IntField("Max Health", m_MaxHP.intValue);
//[Tooltip("per Second")]
m_HealthRegen.floatValue = EditorGUILayout.FloatField("Health Regen", m_HealthRegen.floatValue);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.EndToggleGroup();
//-----MANA----
m_ManaEnabled.boolValue = EditorGUILayout.BeginToggleGroup("Mana", m_ManaEnabled.boolValue);
showManaStats = EditorGUILayout.BeginFoldoutHeaderGroup(showManaStats, "Mana Stats");
if (showManaStats && m_ManaEnabled.boolValue)
{
EditorGUI.indentLevel++;
m_MaxMana.intValue = EditorGUILayout.IntField("Max Mana", m_MaxMana.intValue);
//[Tooltip("per Second")]
m_ManaRegen.floatValue = EditorGUILayout.FloatField("Mana Regen", m_ManaRegen.floatValue);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.EndToggleGroup();
//setting it on stats
//health
serializedObject.FindProperty("m_HealthEnabled").boolValue = m_HealthEnabled.boolValue;
serializedObject.FindProperty("m_MaxHP").intValue = m_MaxHP.intValue;
serializedObject.FindProperty("m_HealthRegen").floatValue = m_HealthRegen.floatValue;
//mana
serializedObject.FindProperty("m_ManaEnabled").boolValue = m_ManaEnabled.boolValue;
serializedObject.FindProperty("m_MaxMana").intValue = m_MaxMana.intValue;
serializedObject.FindProperty("m_ManaRegen").floatValue = m_ManaRegen.floatValue;
serializedObject.ApplyModifiedProperties();
}
}
<file_sep>/In Development Project/Assets/Scripts/Camera/CameraManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraManager : MonoBehaviour
{
[SerializeField] private Camera playerCamera;
[SerializeField] private Camera companionCamera;
private int m_MainCameraLayer = -1;
private int m_SecondaryCameraLayer = -1;
// Start is called before the first frame update
void Start()
{
m_MainCameraLayer = playerCamera.gameObject.layer;
m_SecondaryCameraLayer = companionCamera.gameObject.layer;
}
/// <summary>
/// switches between main and secondary Camera by switching Layers between those and adding+removing appropriate culling masks
/// </summary>
public bool SwitchCamera()
{
if (playerCamera.gameObject.layer == m_MainCameraLayer)
{
playerCamera.gameObject.layer = m_SecondaryCameraLayer;
playerCamera.cullingMask = playerCamera.cullingMask & ~(1 << m_MainCameraLayer); //remove mainCamera
playerCamera.cullingMask = playerCamera.cullingMask | (1 << m_SecondaryCameraLayer); // add secondary Camera
companionCamera.gameObject.layer = m_MainCameraLayer;
companionCamera.cullingMask = companionCamera.cullingMask & ~(1 << m_SecondaryCameraLayer); //remove secondaryCamera
companionCamera.cullingMask = companionCamera.cullingMask | (1 << m_MainCameraLayer); // add main Camera
return true;
}
else if (playerCamera.gameObject.layer == m_SecondaryCameraLayer)
{
playerCamera.gameObject.layer = m_MainCameraLayer;
playerCamera.cullingMask = playerCamera.cullingMask & ~(1 << m_SecondaryCameraLayer); //remove secondary Camera
playerCamera.cullingMask = playerCamera.cullingMask | (1 << m_MainCameraLayer); // add main Camera
companionCamera.gameObject.layer = m_SecondaryCameraLayer;
companionCamera.cullingMask = companionCamera.cullingMask & ~(1 << m_MainCameraLayer); //remove main Camera
companionCamera.cullingMask = companionCamera.cullingMask | (1 << m_SecondaryCameraLayer); // add secondary Camera
return true;
}
return false;
}
}
<file_sep>/In Development Project/Assets/Scripts/Enemy/EnemyBase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Combat;
public class EnemyBase : LivingEntity
{
public GameObject target;
public List<GameObject> RandomWeaponList = new List<GameObject>();
public EnemyBehaviour behaviour = EnemyBehaviour.AGRESSIVE;
public float TargetDetectRange = 20f;
public float AttackDistance = 1.5f;
public float SpotDistance = 5f; // How close until the enemy notices even if not facing target
public float TargetFacingAngle = 20f;
Inventory inventory;
Weapon damageSource;
EnemyState state;
public float AITurnSpeed = 15f;
public float AIMoveSpeed = 4f;
float rayCastOffset = 1.5f;
float detectionDistance = 12f;
List<string> IgnoredObstacleTags = new List<string>{ "Player", "Companion", "Enemy", "Weapon"};
List<EnemyState> NoMovementStates = new List<EnemyState>
{
EnemyState.ATTACK,
EnemyState.HIT
};
List<GameObject> entitiesInRange = new List<GameObject>();
public override void PostStart()
{
inventory = new Inventory(this);
animator = GetComponent<Animator>();
GameObject targetSphere = transform.Find("TargetDetector").gameObject;
targetSphere.GetComponent<SphereCollider>().radius = TargetDetectRange;
if (RandomWeaponList.Count > 0)
{
GameObject choice = RandomWeaponList[Random.Range(0, RandomWeaponList.Count)];
GameObject obj = Instantiate(choice);
Weapon wp = obj.GetComponent<Weapon>();
wp.dropState = DropState.UNCOLLECTABLE;
inventory.addWeapon(wp);
}
}
void Update()
{
FindTarget();
UpdateState();
Pathfinding();
}
void UpdateState()
{
if (target)
{
if(!NoMovementStates.Contains(state) && behaviour == EnemyBehaviour.AGRESSIVE) state = EnemyState.CHASE;
if (getRange(target) == EnemyRange.ATTACK &&
!NoMovementStates.Contains(state) &&
behaviour == EnemyBehaviour.AGRESSIVE) {
if (inventory.hasMainHandWeapon() && inventory.HandWeapon.canAttack())
AttackTarget();
else state = EnemyState.IDLE;
}
}
else state = EnemyState.IDLE;
}
public void entityInsideRange(GameObject entity)
{
if (!entitiesInRange.Contains(entity))
{
entitiesInRange.Add(entity);
}
}
public void entityOutsideRange(GameObject entity)
{
if(entitiesInRange.Contains(entity))
{
entitiesInRange.Remove(entity);
if (target == entity) target = null; // Lost sight of target
}
}
void FindTarget()
{
if (state == EnemyState.ATTACK) return;
List<Transform> byDistance = new List<Transform>();
bool ignoreClose = false;
foreach(GameObject entity in entitiesInRange)
{
EnemyRange range = getRange(entity);
if (range == EnemyRange.SPOTTED) {
byDistance.Add(entity.transform);
ignoreClose = true;
}
else if(range == EnemyRange.INRANGE && !ignoreClose)
{
byDistance.Add(entity.transform);
}
}
if (byDistance.Count == 0) return;
if(ignoreClose)
{
Transform closest = getClosestFromTransformList(byDistance);
target = closest.gameObject;
}
else
{
// Filter only targets that are facing us
List<Transform> facing = new List<Transform>();
foreach(Transform entity in byDistance)
{
if (Vector3.Angle(entity.forward, transform.position - entity.position) < TargetFacingAngle)
{
facing.Add(entity);
}
}
if (facing.Count == 0) return;
Transform closest = getClosestFromTransformList(facing);
target = closest.gameObject;
}
}
Transform getClosestFromTransformList(List<Transform> list)
{
Transform closest = null;
foreach (Transform entity in list)
{
if (closest != null && (Vector3.Distance(transform.position, entity.position) <
Vector3.Distance(transform.position, closest.position)))
{
closest = entity;
}
else if (closest == null) closest = entity;
else continue;
}
return closest;
}
EnemyRange getRange(GameObject entity)
{
float distance = Vector3.Distance(transform.position, entity.transform.position);
EnemyRange range;
if (distance <= AttackDistance)
range = EnemyRange.ATTACK;
else if (distance <= SpotDistance)
range = EnemyRange.SPOTTED;
else
range = EnemyRange.INRANGE;
return range;
}
public override void handleHitByWeapon(Weapon weapon)
{
if (weapon.isReady() && !takingDamageFrom(weapon) && inventory.HandWeapon != weapon)
{
if (inventory.HandWeapon && inventory.HandWeapon.isReady()) inventory.HandWeapon.cancelAttack();
weapon.weaponHitEnemy();
StartCoroutine(TakeDamage(weapon));
}
}
bool takingDamageFrom(Weapon weapon)
{
return damageSource == weapon;
}
IEnumerator TakeDamage(Weapon source)
{
state = EnemyState.HIT;
damageSource = source;
playHitAnimation();
takeDamage(source.DamageAmount);
yield return new WaitForSeconds(2f);
state = EnemyState.IDLE;
damageSource = null;
}
void playHitAnimation()
{
animator.SetTrigger("GutHit");
}
void Pathfinding()
{
if (state == EnemyState.CHASE)
{
RaycastHit hit;
RaycastHit hit2;
Vector3 turnOffset = Vector3.zero;
Vector3 left = (transform.position - transform.forward * rayCastOffset) - transform.right * rayCastOffset;
Vector3 right = (transform.position - transform.forward * rayCastOffset) + transform.right * rayCastOffset;
Vector3 mid = (transform.position - transform.forward * rayCastOffset);
if (Physics.Raycast(mid, transform.forward, out hit2, detectionDistance ))
{
if (Physics.Raycast(left, transform.forward, out hit, detectionDistance))
{
if (isObstacle(hit))
turnOffset += Vector3.right;
}
else if (Physics.Raycast(right, transform.forward, out hit, detectionDistance))
{
if (isObstacle(hit))
turnOffset -= Vector3.right;
}
}
EnemyRange range = getRange(target);
if (turnOffset != Vector3.zero && range != EnemyRange.ATTACK)
{
transform.rotation = Quaternion.Euler(transform.eulerAngles.x,
transform.eulerAngles.y + (turnOffset.x * AITurnSpeed * Time.deltaTime),
transform.eulerAngles.z);
}
else
TurnTorwardsPlayer();
MoveTorwardsPlayer();
animator.SetBool("Walking", true);
}
else if(state == EnemyState.ATTACK)
{
TurnTorwardsPlayer();
}
else if(state == EnemyState.IDLE)
{
animator.SetBool("Walking", false);
}
}
bool isObstacle(RaycastHit hit)
{
if (!IgnoredObstacleTags.Contains(hit.collider.tag) &&
!hit.collider.GetComponent<Terrain>()) // Temporary method of detecting ground!!!
return true;
return false;
}
void TurnTorwardsPlayer()
{
Vector3 pos = target.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(pos);
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.Euler(new Vector3(transform.eulerAngles.x, rotation.eulerAngles.y, transform.eulerAngles.z)),
(AITurnSpeed / 2) * Time.deltaTime);
}
void MoveTorwardsPlayer()
{
transform.position += transform.forward * AIMoveSpeed * Time.deltaTime;
}
void AttackTarget()
{
if(state != EnemyState.ATTACK)
{
state = EnemyState.ATTACK;
inventory.HandWeapon.basicAttack();
}
}
public override void basicAttackDone()
{
state = EnemyState.CHASE;
}
public override Transform findWeaponOrigin()
{
return transform.GetChild(0).GetChild(2).GetChild(2).GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0).GetChild(0).Find("WeaponOrigin");
}
public override Transform findBackOrigin()
{
return transform.GetChild(0).GetChild(2).GetChild(2).GetChild(0).Find("BackItemAttach");
}
}
<file_sep>/In Development Project/Assets/Scripts/Weapons/MagicStaff.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Combat
{
public class MagicStaff : Weapon
{
float Range = 10f;
float TravelSpeed = 1f;
ParticleSystem MagicOrb;
Transform orbRest;
Vector3 destination = Vector3.zero;
public override void postStart()
{
MagicOrb = transform.Find("MagicOrb").GetComponent<ParticleSystem>();
orbRest = transform.Find("OrbRestPos");
MagicOrb.gameObject.GetComponent<MagicStaffOrb>().setStaff(this);
}
public override void postUpdate()
{
if (MagicOrb.isPlaying)
{
if (destination == Vector3.zero) destination = MagicOrb.transform.position + orbRest.TransformDirection((Vector3.up * Range) + new Vector3(4, 0, -1));
MagicOrb.transform.LookAt(destination);
MagicOrb.transform.position =
Vector3.Lerp(MagicOrb.transform.position, destination, TravelSpeed * Time.deltaTime);
}
else
{
destination = Vector3.zero;
MagicOrb.transform.parent = transform;
MagicOrb.transform.position = orbRest.position;
}
}
public override void basicAttack()
{
if (canAttack())
{
StartCoroutine("playBasicAttack");
}
else
{
entity.basicAttackDone();
}
}
public override void cancelAttack()
{
StopCoroutine("playBasicAttack");
unreadyWeapon();
MagicOrb.Stop();
entity.basicAttackDone();
}
IEnumerator playBasicAttack()
{
lastUse = Time.time;
entity.basicAttackStarted();
entity.animator.SetTrigger("UseMagicStaff");
yield return new WaitForSeconds(0.9f);
MagicOrb.transform.parent = null;
readyWeapon();
MagicOrb.Play();
yield return new WaitForSeconds(AnimDuration - 0.9f);
if (MagicOrb.isPlaying) MagicOrb.Stop();
unreadyWeapon();
entity.basicAttackDone();
}
public override void weaponHitEnemy()
{
MagicOrb.Stop();
}
}
}<file_sep>/In Development Project/Assets/Scripts/Stats/ManaComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ManaComponent : ResourceComponent
{
private float m_ManaRegen = 0f;
public ManaComponent(int maxMana, float manaRegen)
{
m_MaxAmount = maxMana;
m_CurrentResource = maxMana;
m_ManaRegen = manaRegen;
}
}
<file_sep>/In Development Project/Assets/Scripts/Enemy/EnemyUtil.cs
using System.Collections;
using System.Collections.Generic;
enum EnemyRange {
ATTACK,
SPOTTED,
INRANGE
}
enum EnemyState
{
IDLE,
CHASE,
ATTACK,
HIT
}
public enum EnemyBehaviour
{
PASSIVE,
AGRESSIVE
}<file_sep>/In Development Project/Assets/Scripts/Weapons/Weapon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Combat
{
public class Weapon : MonoBehaviour
{
public DropState dropState = DropState.COLLECTABLE;
public float DamageAmount;
public float AnimDuration = 1.5f;
public float Cooldown = 0.5f;
public Vector3 AttachToHandPosition;
public Vector3 AttachToHandRotation;
public Vector3 BackPlacePosition;
public Vector3 BackPlaceRotation;
SphereCollider DropCollider;
Transform weaponOrigin;
Transform backOrigin;
[HideInInspector] public float lastUse = -1;
[HideInInspector] public WeaponState weaponState = WeaponState.UNREADY;
[HideInInspector] public LivingEntity entity;
void Start()
{
DropCollider = GetComponent<SphereCollider>();
postStart();
}
public virtual void postStart()
{
}
// Update is called once per frame
void Update()
{
postUpdate();
}
public virtual void postUpdate()
{
}
private void OnTriggerEnter(Collider other)
{
if (dropState == DropState.COLLECTABLE)
{
if (other.tag == "Player" || other.tag == "Companion")
{
bool success = other.GetComponent<PlayerBase>().AttemptPickup(this);
if (success)
{
dropState = DropState.UNCOLLECTABLE;
}
}
}
}
public virtual void attachWeaponToHand()
{
weaponOrigin.localPosition = AttachToHandPosition;
weaponOrigin.localRotation = Quaternion.Euler(AttachToHandRotation);
transform.parent = weaponOrigin;
transform.position = weaponOrigin.position;
transform.rotation = weaponOrigin.rotation;
}
public virtual void attachWeaponToBack()
{
backOrigin.localPosition = BackPlacePosition;
backOrigin.localRotation = Quaternion.Euler(BackPlaceRotation);
transform.parent = backOrigin;
transform.position = backOrigin.position;
transform.rotation = backOrigin.rotation;
}
public void readyWeapon()
{
DropCollider.enabled = false;
weaponState = WeaponState.READY;
}
public void unreadyWeapon()
{
DropCollider.enabled = true;
weaponState = WeaponState.UNREADY;
}
public bool isReady()
{
return weaponState == WeaponState.READY;
}
public bool canAttack()
{
return (Time.time > lastUse + AnimDuration + Cooldown) || lastUse == -1;
}
public void weaponAttachedToEntity(LivingEntity e)
{
entity = e;
weaponOrigin = entity.findWeaponOrigin();
backOrigin = entity.findBackOrigin();
}
public virtual void weaponHitEnemy()
{
}
public virtual void basicAttack()
{
}
public virtual void cancelAttack()
{
}
}
}<file_sep>/In Development Project/Assets/Scripts/Player/PlayerBase.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Combat;
public class PlayerBase : LivingEntity
{
[HideInInspector] public Inventory inventory;
[HideInInspector] public PlayerMovement movement;
Weapon damageSource;
bool castingBasicAttack;
bool listenInput = true;
bool canAttack = true;
public override void PostStart()
{
inventory = new Inventory(this);
animator = transform.GetComponent<Animator>();
movement = GetComponent<PlayerMovement>();
}
private void Update()
{
UpdateInput();
}
public void setActivePlayer(bool isActive)
{
listenInput = isActive;
}
void UpdateInput()
{
if (listenInput)
{
if (Input.GetMouseButton(0) && !castingBasicAttack && canAttack)
{
CastBasicAttack();
}
if (Input.GetKeyUp(KeyCode.Tab) && !castingBasicAttack)
{
inventory.SwitchWeapons();
}
}
}
void CastBasicAttack()
{
if(inventory.hasMainHandWeapon())
{
castingBasicAttack = true;
inventory.HandWeapon.basicAttack();
}
}
public override void basicAttackStarted()
{
movement.disableMovement();
}
public override void basicAttackDone()
{
movement.enableMovement();
castingBasicAttack = false;
}
public bool AttemptPickup(Weapon weapon)
{
if(hasWeaponSpace(weapon))
{
inventory.addWeapon(weapon);
return true;
}
return false;
}
bool hasWeaponSpace(Weapon weapon)
{
return !inventory.isFullOfWeapons();
}
public override Transform findWeaponOrigin()
{
return transform.GetChild(0).GetChild(2).GetChild(2).GetChild(0).GetChild(0).GetChild(2).GetChild(0).GetChild(0).GetChild(0).Find("WeaponOrigin");
}
public override Transform findBackOrigin()
{
return transform.GetChild(0).GetChild(2).GetChild(2).GetChild(0).Find("BackItemAttach");
}
public override void handleHitByWeapon(Weapon weapon)
{
if (weapon.isReady() && !takingDamageFrom(weapon) && inventory.HandWeapon != weapon)
{
if (inventory.HandWeapon && inventory.HandWeapon.isReady()) inventory.HandWeapon.cancelAttack();
weapon.weaponHitEnemy();
StartCoroutine(TakeDamage(weapon));
}
}
bool takingDamageFrom(Weapon weapon)
{
return damageSource == weapon;
}
IEnumerator TakeDamage(Weapon source)
{
canAttack = false;
damageSource = source;
animator.SetTrigger("GutHit");
movement.disableMovement();
takeDamage(source.DamageAmount);
yield return new WaitForSeconds(source.AnimDuration - 0.5f);
movement.enableMovement();
canAttack = true;
yield return new WaitForSeconds(0.5f);
damageSource = null;
}
}
<file_sep>/In Development Project/Assets/Scripts/UI/HealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthBar : MonoBehaviour
{
[SerializeField] HealthComponent healthComponent = null;
[SerializeField] RectTransform foreground = null;
void Update()
{
//foreground.localScale = new Vector3(healthComponent.getPercentage(), 1, 1);
}
}
<file_sep>/In Development Project/Assets/Scripts/Player/Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Combat;
public class Inventory
{
public int MaxWeapons = 2;
List<Weapon> weapons = new List<Weapon>();
public Weapon HandWeapon = null;
public Weapon BackWeapon = null;
LivingEntity entity;
public Inventory(LivingEntity _p)
{
entity = _p;
}
public void addWeapon(Weapon weapon)
{
if (!isFullOfWeapons() && ! weapons.Contains(weapon))
{
weapons.Add(weapon);
organizeWeapons();
}
}
public bool isFullOfWeapons()
{
return weapons.Count >= MaxWeapons;
}
public bool hasMainHandWeapon()
{
return HandWeapon != null;
}
void organizeWeapons()
{
foreach (Weapon weapon in weapons)
{
if (HandWeapon == null && !isAssigned(weapon))
{
HandWeapon = weapon;
HandWeapon.weaponAttachedToEntity(entity);
HandWeapon.attachWeaponToHand();
}
else if (BackWeapon == null && !isAssigned(weapon))
{
BackWeapon = weapon;
BackWeapon.weaponAttachedToEntity(entity);
BackWeapon.attachWeaponToBack();
}
}
}
public void SwitchWeapons()
{
Weapon HW = HandWeapon;
Weapon BW = BackWeapon;
if (HW && BW)
{
HandWeapon = BW;
BackWeapon = HW;
HandWeapon.attachWeaponToHand();
BackWeapon.attachWeaponToBack();
}
}
bool isAssigned(Weapon weapon)
{
return HandWeapon == weapon || BackWeapon == weapon;
}
}
<file_sep>/In Development Project/Assets/Scripts/Movement/LocomotionNavAgent.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(Animator))]
public class LocomotionNavAgent : MonoBehaviour
{
[Header("Steering")]
[SerializeField] private float m_NavAgentSpeed = 7.5f;
[SerializeField] private float m_NavAgentAngularSpeed = 180f;
[SerializeField] private float m_NavAgentAccel = 20f;
[SerializeField] private float m_NavAgentStoppingDistance = 3f;
[SerializeField] private bool m_NavAgentAutoBraking = true;
[Header("Object Settings")]
[SerializeField] private Transform m_Target = null; // TODO: Set from some kind of Manager/Handler/etc.
[SerializeField] [Tooltip("inverted Y position from children mesh")] private float m_YOffset = 0f;
private NavMeshAgent m_NavMeshAgent = null;
private Animator m_Animator = null;
private Vector2 m_SmoothDeltaPosition = Vector2.zero;
private Vector2 m_Velocity = Vector2.zero;
private Vector3 m_YOffsetV3 = Vector3.zero;
private bool m_ShouldFollow = false;
// Start is called before the first frame update
void Start()
{
m_Animator = GetComponent<Animator>();
//m_NavMeshAgent = GetComponent<NavMeshAgent>();
AddNavMeshAgent();
m_NavMeshAgent.updatePosition = false;
m_YOffsetV3 = new Vector3(0f, m_YOffset, 0f);
}
private void AddNavMeshAgent()
{
m_NavMeshAgent = gameObject.AddComponent<NavMeshAgent>();
m_NavMeshAgent.speed = m_NavAgentSpeed;
m_NavMeshAgent.angularSpeed = m_NavAgentAngularSpeed;
m_NavMeshAgent.acceleration = m_NavAgentAccel;
m_NavMeshAgent.stoppingDistance = m_NavAgentStoppingDistance;
m_NavMeshAgent.autoBraking = m_NavAgentAutoBraking;
}
/// <summary>
/// enable following Target
/// </summary>
internal void EnableFollow()
{
m_NavMeshAgent.enabled = true;
}
/// <summary>
/// disable following Target
/// </summary>
internal void DisableFollow()
{
//m_NavMeshAgent.isStopped = true; //test if it makes a difference
//m_NavMeshAgent.updatePosition = false; //test if it makes a difference
//m_NavMeshAgent.updateRotation = false; //test if it makes a difference
m_NavMeshAgent.enabled = false;
}
void Update()
{
FollowTarget();
}
/// <summary>
/// sets NavMeshAgent Destination to target position, smoothes the deltaPosition between this position and next Position of the agent
/// sets Animator Float "Speed" to desired velocity
/// </summary>
private void FollowTarget()
{
if (m_NavMeshAgent.enabled)
{
m_NavMeshAgent.SetDestination(m_Target.position);
Vector3 worldDeltaPosition = m_NavMeshAgent.nextPosition - transform.position;
// Map 'worldDeltaPosition' to local space
float dx = Vector3.Dot(transform.right, worldDeltaPosition);
float dy = Vector3.Dot(transform.forward, worldDeltaPosition);
Vector2 deltaPosition = new Vector2(dx, dy);
// Low-pass filter the deltaMove
float smooth = Mathf.Min(1.0f, Time.deltaTime / 0.15f);
m_SmoothDeltaPosition = Vector2.Lerp(m_SmoothDeltaPosition, deltaPosition, smooth);
// Update velocity if time advances
if (Time.deltaTime > 1e-5f)
{
m_Velocity = m_SmoothDeltaPosition / Time.deltaTime;
}
bool shouldMove = m_Velocity.magnitude > 0.5f && m_NavMeshAgent.remainingDistance > m_NavMeshAgent.radius;
// Update animation parameter(s)
m_Animator.SetFloat("Speed", m_Velocity.x + m_Velocity.y);
}
}
/// <summary>
/// gets called by Animator Component, sets transform position to nav mesh agents next position
/// </summary>
void OnAnimatorMove()
{
if (m_NavMeshAgent.enabled)
{
// Update position to agent position
transform.position = m_NavMeshAgent.nextPosition + m_YOffsetV3;
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Meta/CharacterSwitchCoordinator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class CharacterSwitchCoordinator : MonoBehaviour
{
private CameraManager m_CameraManager = null;
//---------Player------------
private GameObject m_Player = null;
private PlayerMovement m_PlayerMovement = null;
private LocomotionNavAgent m_PlayerNavAgent = null;
private PlayerBase m_PlayerBase = null;
//---------Companion------------
private GameObject m_Companion = null;
private PlayerMovement m_CompanionMovement = null;
private LocomotionNavAgent m_CompanionNavAgent = null;
private PlayerBase m_CompanionBase = null;
private void Start()
{
//----Setup----
m_CameraManager = FindObjectOfType<CameraManager>();
m_Player = GameObject.FindGameObjectWithTag("Player");
m_PlayerMovement = m_Player.GetComponent<PlayerMovement>();
m_PlayerNavAgent = m_Player.GetComponent<LocomotionNavAgent>();
m_PlayerBase = m_Player.GetComponent<PlayerBase>();
m_Companion = GameObject.FindGameObjectWithTag("Companion");
m_CompanionMovement = m_Companion.GetComponent<PlayerMovement>();
m_CompanionNavAgent = m_Companion.GetComponent<LocomotionNavAgent>();
m_CompanionBase = m_Companion.GetComponent<PlayerBase>();
m_PlayerNavAgent.DisableFollow(); //TODO: Initialize states in gameManager
m_CompanionBase.setActivePlayer(false);
m_CompanionMovement.disableMovement(); //TODO: Initialize states in gameManager
m_CompanionNavAgent.EnableFollow(); //TODO: Initialize states in gameManager
}
/// <summary>
/// Handles Input //TODO: Move to InputManager
/// </summary>
private void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
SwitchCharacters();
}
}
/// <summary>
/// Handles switching of context between the 2 characters
/// </summary>
/// <returns>true if successful</returns>
public bool SwitchCharacters()
{
//EnableDisable relevant Components on GameObjects
if (SwitchComponents() && m_CameraManager.SwitchCamera())
{
return true;
}
return false;
}
/// <summary>
/// toggles all relevant components between the 2 characters
///
/// </summary>
/// <returns>true if components were switched</returns>
private bool SwitchComponents()
{
if (m_CompanionMovement.CanMove && !m_PlayerMovement.CanMove)//TODO: Use flags from central Game object component instead
{
m_CompanionBase.setActivePlayer(false);
m_CompanionMovement.disableMovement();
m_CompanionNavAgent.EnableFollow();
m_PlayerBase.setActivePlayer(true);
m_PlayerMovement.enableMovement();
m_PlayerNavAgent.DisableFollow();
return true;
}
else if (!m_CompanionMovement.CanMove && m_PlayerMovement.CanMove)
{
m_PlayerBase.setActivePlayer(false);
m_PlayerMovement.disableMovement();
m_PlayerNavAgent.EnableFollow();
m_CompanionBase.setActivePlayer(true);
m_CompanionMovement.enableMovement();
m_CompanionNavAgent.DisableFollow();
return true;
}
else
{
Debug.LogWarning("MovementComponents on player and Companion not in sync (off+on or on+off)");
return false;
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Stats/Stats.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum StatType
{
Health, Mana
}
public class Stats : MonoBehaviour
{
//------HEALTH-----
[HideInInspector] [SerializeField] public bool m_HealthEnabled = true;
[HideInInspector] [SerializeField] public int m_MaxHP = 100;
[HideInInspector] [SerializeField] public float m_HealthRegen = 2f;
//------MANA-----
[HideInInspector] public bool m_ManaEnabled;
[HideInInspector] [SerializeField] public int m_MaxMana = 50;
[HideInInspector] [SerializeField] public float m_ManaRegen = 1f;
private Dictionary<StatType, ResourceComponent> m_Stats = new Dictionary<StatType, ResourceComponent>();
// Start is called before the first frame update
void Awake()
{
AddStatComponents();
}
private void AddStatComponents()
{
if (m_HealthEnabled)
{
m_Stats.Add(StatType.Health, new HealthComponent(m_MaxHP, m_HealthRegen));
}
if (m_ManaEnabled)
{
m_Stats.Add(StatType.Mana, new ManaComponent(m_MaxMana, m_ManaRegen));
}
}
// Update is called once per frame
void Update()
{
//Regen Stats
}
public ResourceComponent Get(StatType statType)
{
switch (statType)
{
case (StatType.Health):
{
ResourceComponent healthComp;
m_Stats.TryGetValue(StatType.Health,out healthComp);
return healthComp != null ? healthComp : null;
}
case (StatType.Mana):
{
ResourceComponent manaComp;
m_Stats.TryGetValue(StatType.Mana, out manaComp);
return manaComp != null ? manaComp : null;
}
default:
{
Debug.LogWarning("undefined statType");
return null;
}
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Stats/HealthComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthComponent : ResourceComponent
{
private float m_HealthRegen = 0f;
public HealthComponent(float maxHP, float healthRegen)
{
m_CurrentResource = maxHP;
m_MaxAmount = maxHP;
m_HealthRegen = healthRegen;
}
}
<file_sep>/In Development Project/Assets/Scripts/Weapons/MagicStaffOrb.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Combat
{
public class MagicStaffOrb : MonoBehaviour
{
MagicStaff staff;
public void setStaff(MagicStaff s)
{
staff = s;
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Enemy")
{
if (staff)
{
other.GetComponent<EnemyBase>().handleHitByWeapon(staff);
}
}
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Movement/PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController characterController;
private Animator animator;
[SerializeField] private float forwardMoveSpeed = 7.5f;
[SerializeField] private float backwardMoveSpeed = 3;
[SerializeField] private float turnSpeed = 150f;
[HideInInspector] bool canMove = true;
public bool CanMove {
get { return canMove; }
}
private void Awake()
{
characterController = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
Cursor.lockState = CursorLockMode.Locked;
}
public void disableMovement()
{
animator.SetFloat("Speed", 0);
canMove = false;
}
public void enableMovement()
{
canMove = true;
}
private void Update()
{
if (!canMove) return;
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var movement = new Vector3(horizontal, 0, vertical);
animator.SetFloat("Speed", vertical);
transform.Rotate(Vector3.up, horizontal * turnSpeed * Time.deltaTime);
if (vertical != 0)
{
float moveSpeedToUse = vertical > 0 ? forwardMoveSpeed : backwardMoveSpeed;
characterController.SimpleMove(transform.forward * moveSpeedToUse * vertical);
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Weapons/WeaponUtil.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum DropState
{
COLLECTABLE,
UNCOLLECTABLE
}
public enum WeaponState
{
READY,
UNREADY
}
<file_sep>/In Development Project/Assets/Scripts/Weapons/Sword.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Combat
{
public class Sword : Weapon
{
ParticleSystem SwingEffect;
public override void postStart()
{
SwingEffect = transform.Find("SwingEffect").GetComponent<ParticleSystem>();
}
public override void basicAttack()
{
if (canAttack())
{
StartCoroutine("playBasicAttack");
}
else
{
entity.basicAttackDone();
}
}
public override void cancelAttack()
{
StopCoroutine("playBasicAttack");
unreadyWeapon();
SwingEffect.Stop();
entity.basicAttackDone();
}
IEnumerator playBasicAttack()
{
lastUse = Time.time;
entity.basicAttackStarted();
entity.animator.SetTrigger("SwordSlash");
yield return new WaitForSeconds(0.7f);
SwingEffect.Play();
readyWeapon();
yield return new WaitForSeconds(AnimDuration - 0.7f);
SwingEffect.Stop();
unreadyWeapon();
entity.basicAttackDone();
}
}
}<file_sep>/In Development Project/Assets/Scripts/Effects/Shine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shine : MonoBehaviour
{
public float ColorBlendTime = 1f;
bool playGlowOut;
bool playGlowIn;
Color GlowOutColor = new Color(0, 0, 0, 1);
Color GlowInColor = new Color(0.706f, 0.537f, 0.122f, 1);
// Start is called before the first frame update
void Start()
{
getMat().EnableKeyword("_EmissionColor");
StartCoroutine("PlayShine");
}
public void disableShine()
{
StopCoroutine("PlayShine");
playGlowIn = false;
playGlowOut = false;
getMat().SetColor("_EmissionColor", new Color(0, 0, 0, 1));
}
Material getMat()
{
return GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update()
{
Material mat = getMat();
if(playGlowOut)
{
Color color = Color.Lerp(mat.GetColor("_EmissionColor"), GlowOutColor, ColorBlendTime * Time.deltaTime);
mat.SetColor("_EmissionColor", color);
}
else if(playGlowIn)
{
Color color = Color.Lerp(mat.GetColor("_EmissionColor"), GlowInColor, ColorBlendTime * Time.deltaTime);
mat.SetColor("_EmissionColor", color);
}
}
IEnumerator PlayShine()
{
while (true)
{
playGlowIn = false;
playGlowOut = true;
yield return new WaitForSeconds(2);
playGlowOut = false;
playGlowIn = true;
yield return new WaitForSeconds(2);
}
}
}
<file_sep>/In Development Project/Assets/Scripts/Enemy/EnemyTargetTrigger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTargetTrigger : MonoBehaviour
{
EnemyBase enemy;
void Start()
{
enemy = GetComponentInParent<EnemyBase>();
}
private void OnTriggerEnter(Collider other)
{
if(other.tag != "Enemy" && other.gameObject.GetComponent<LivingEntity>())
{
enemy.entityInsideRange(other.gameObject);
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag != "Enemy" && other.gameObject.GetComponent<LivingEntity>())
{
enemy.entityOutsideRange(other.gameObject);
}
}
}
| 878dba0349dd6137e811d0e61ed554b3b352e9c1 | [
"C#"
] | 22 | C# | ZanSaito/InDevelopment | 5be0a39c76e7675a529297cb11173f41c286527a | 67cefcea79d723805797744565a2e538f1bec78b |
refs/heads/master | <repo_name>darrdv/ruby_fundamentals1<file_sep>/exercise4.rb
one_to_hundred = (1..100)
one_to_hundred.each do |num|
string_array = []
flag = 0
if num % 3 == 0
string_array.push('Bit')
flag = 1
end
if num % 5 == 0
string_array.push('Maker')
flag = 1
end
if flag == 0
puts num
else
puts string_array.join("")
end
end
<file_sep>/exercise2.rb
#1. The cost of good meal would be its cost (55 dollars) multiplied by 15 %
puts "Here's the tip: #{55 * 0.15}!"
#2. Adding a string and an integer, you get a big TypeError message
# "10" + 10
#converting integer to string and using puts to display the result.
number_ten = 10
string_ten = number_ten.to_s
puts "#{string_ten} + #{number_ten}"
#3. Using string interpolation
puts "When we multiply 45628 by 7839, we get: #{45628 * 7839}. "
#4. The value is true.
puts "#{(10 < 20 && 30 < 20) || !(10 == 11)}"
| aa20bf646c9546207b9994b3f218160d1f6b8be3 | [
"Ruby"
] | 2 | Ruby | darrdv/ruby_fundamentals1 | 57ca3ad09726fe65cee2f79c882843fe38ebfb16 | 303665859b9c6892077e0962638c72442c479f0a |
refs/heads/master | <file_sep>
Components.utils.import("chrome://jam-extension/content/log4moz.js");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
// Loggers are hierarchical, lowering this log level will affect all
// output.
root.level = Log4Moz.Level["All"];
// this appender will log to the file system.
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
var logger = Log4Moz.repository.getLogger("common");
logger.level = Log4Moz.Level["All"];
var wpl = Components.interfaces.nsIWebProgressListener;
var wplFlags = { //nsIWebProgressListener state transition flags
STATE_START: wpl.STATE_START,
STATE_STOP: wpl.STATE_STOP,
STATE_REDIRECTING: wpl.STATE_REDIRECTING,
STATE_TRANSFERRING: wpl.STATE_TRANSFERRING,
STATE_NEGOTIATING: wpl.STATE_NEGOTIATING,
STATE_IS_REQUEST: wpl.STATE_IS_REQUEST,
STATE_IS_DOCUMENT: wpl.STATE_IS_DOCUMENT,
STATE_IS_NETWORK: wpl.STATE_IS_NETWORK,
STATE_RESTORING: wpl.STATE_RESTORING,
LOCATION_CHANGE_SAME_DOCUMENT: wpl.LOCATION_CHANGE_SAME_DOCUMENT,
LOCATION_CHANGE_ERROR_PAGE: wpl.LOCATION_CHANGE_ERROR_PAGE,
};
function flagString(aFlag) {
var ret = undefined;
for (var f in wplFlags) {
if (wplFlags[f] & aFlag) {
if (ret === undefined) {
ret = f;
} else {
ret += '|' + f;
}
}
}
if (ret === undefined) {
return aFlag + ' (unknown)';
}
return aFlag + ' (' + ret + ')';
}
function loadFromFile(filename, obj, propId) {
let path = getLocalDirectory();
path.append(filename);
logger.info('Loading file ' + path.path);
if (path.exists()) {
NetUtil.asyncFetch(path, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
logger.error('Unable to open policy file: ' + path.path);
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
obj[propId] = data;
});
} else {
obj[propId] = null;
}
}
var jaminfo = {
policies: {},
}
var myListener = {
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener", "nsISupportsWeakReference"]),
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
// If you use myListener for more than one tab/window, use
// aWebProgress.DOMWindow to obtain the tab/window which triggers the state change
var win = aWebProgress.DOMWindow;
var aname = aRequest ? aRequest.name : aRequest;
logger.info('StateChange: aFlag=' + flagString(aFlag) + ', aRequest=' + aname + ', aStatus=' + aStatus + ' win: ' + win);
if (!isEnabled())
return;
if ((aFlag & wpl.STATE_TRANSFERRING) && (aFlag & wpl.STATE_IS_REQUEST) && (aFlag & wpl.STATE_IS_DOCUMENT)) {
// In UDJ, we don't transitively secure frames, but rather load
// the policy and library anew for each frame.
if (win /*&& win === win.top*/) {
for (var polid in jaminfo.policies) {
if (jaminfo.policies[polid] === true) {
var polfile = 'policy-' + polid + '.js';
Services.scriptloader.loadSubScript('chrome://jam-extension/content/' + polfile, win, 'UTF-8');
}
}
Services.scriptloader.loadSubScript('chrome://jam-extension/content/libTx.js', win, 'UTF-8');
logger.info("LOADED");
} else {
logger.warn('No window available');
}
}
},
onLocationChange: function(aProgress, aRequest, aURI, aFlag) {
// This fires when the location bar changes; that is load event is confirmed
// or when the user switches tabs. If you use myListener for more than one tab/window,
// use aProgress.DOMWindow to obtain the tab/window which triggered the change.
var aname = aRequest ? aRequest.name : aRequest;
logger.info('LocationChange: aFlag=' + flagString(aFlag) + ', aRequest=' + aname + ', aURI=' + aURI.spec);
},
// For definitions of the remaining functions see related documentation
onProgressChange: function(aWebProgress, aRequest, curSelf, maxSelf, curTot, maxTot) {
var aname = aRequest ? aRequest.name : aRequest;
logger.info('ProgressChange: aRequest=' + aname + ', curSelf=' + curSelf + ', maxSelf=' + maxSelf + ', curTot=' + curTot + ', maxTot=' + maxTot);
/*
var win = aWebProgress.DOMWindow;
// iframes are transitively handled by other mechanisms.
if (win && win === win.top) {
Services.scriptloader.loadSubScript('chrome://jam-extension/content/policy.js', win, 'UTF-8');
Services.scriptloader.loadSubScript('chrome://jam-extension/content/libTx.js', win, 'UTF-8');
logger.info("LOADEDED");
} else {
logger.warn('No window available');
}
*/
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {
var aname = aRequest ? aRequest.name : aRequest;
logger.info('StatusChange: aStatus=' + aStatus + ', aRequest=' + aname + ', aMessage=' + aMessage);
},
onSecurityChange: function(aWebProgress, aRequest, aState) {
var aname = aRequest ? aRequest.name : aRequest;
logger.info('SecurityChange: aRequest=' + aname + ', aState=' + aState);
},
}
function getLocalDirectory() {
let directoryService =
Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Components.interfaces.nsIFile);
localDir.append("jam-extension");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
function doHttpRequest(script,data) {
debugln('-------------------');
debugln('request to: ' + script);
debugln(' data: ' + data);
data = data + '';
var req = new XMLHttpRequest();
req.open('POST', script, false );
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setRequestHeader('Content-Length', data.length);
req.send(data);
debugln(' response: ' + req.responseText);
return req.responseText;
}
function xmldecode(val) {
val = val.replace(/"/ig, "'");
val = val.replace(/</ig, "<");
val = val.replace(/>/ig, ">");
val = val.replace(/&/ig, "&");
return val;
}
function plaintextencode(val) {
val = val.replace(/&/ig, "&");
val = val.replace(/</ig, "<");
val = val.replace(/>/ig, ">");
val = val.replace(/\x22/ig, """);
val = val.replace(/\n/ig, "<br>");
val = val.replace(/\r/ig, "");
return val;
}
function browserListen(browser) {
browser.webProgress.addProgressListener(myListener, browser.webProgress.NOTIFY_ALL);
}
function browserForget(browser) {
browser.webProgress.removeProgressListener(myListener);
}
function tabListen(ev) {
var tab = ev.target;
var browser = gBrowser.getBrowserForTab(tab);
browserListen(browser);
}
function tabForget(browser) {
var tab = ev.target;
var browser = gBrowser.getBrowserForTab(tab);
browserForget(browser);
}
function isEnabled() {
for (var polid in jaminfo.policies) {
if (jaminfo.policies[polid] === true) {
return true;
}
}
return false;
}
function doToggle(eltid) {
var chk = document.getElementById('chk' + eltid);
var val = chk.checked;
// See if there are any policies enabled initially.
var presome = isEnabled();
// Track if there are any policies enabled still.
var postsome = false;
if (val) {
jaminfo.policies[eltid] = true;
postsome = true;
} else {
jaminfo.policies[eltid] = false;
postsome = isEnabled();
}
if (presome !== postsome) {
if (postsome) {
gBrowser.browsers.forEach(function (browser) {
browserListen(browser);
});
} else {
gBrowser.browsers.forEach(function (browser) {
browserForget(browser);
});
}
}
logger.info('Toggled: ' + val);
}
gBrowser.tabContainer.addEventListener("TabOpen", tabListen, false);
gBrowser.tabContainer.addEventListener("TabClose", tabForget, false);
<file_sep>#!/bin/bash
# !!! edit install.rdf to indicate new version number
# %%% Take version number as input and use sed to change install.rdf.
projname=extension
projdir=~/cs/jam/$projname
jarname=jam-extension
cmpdir=$projdir/compile
# copy the 'src' folder to a new one called 'compile'
rm -rf $cmpdir
cp -r $projdir/src $cmpdir
# save appropriate form of chrome.manifest
mv $cmpdir/chrome-RELEASE.manifest $cmpdir/chrome.manifest
rm -f $cmpdir/chrome-DEBUG.manifest
# run the following 2 commands
cd $cmpdir/chrome/$jarname
jar cvf $jarname.jar *
cd -
# move $jarname.jar up one level
mv $cmpdir/chrome/$jarname/$jarname.jar $cmpdir/chrome/
# delete the '$jarname' folder
rm -rf $cmpdir/chrome/$jarname
# Zip chrome, chrome.manifest, install.rdf into hsadmin.xpi
cd $cmpdir
zip $jarname.xpi chrome/$jarname.jar chrome.manifest install.rdf
cd -
# change $jarname-update.rdf to indicate the new version number
# upload $jarname-update.rdf and to website $jarname.xpi to the web server
<file_sep>var policy = function() {
var _Location_prototype_reload = Location.prototype.reload;
var _Location_prototype_replace = Location.prototype.replace;
var _Location_prototype_assign = Location.prototype.assign;
var _Window = Window;
var _Location = Location;
var _HTMLFormElement_prototype_submit = HTMLFormElement.prototype.submit;
function pFull(tx) {
var commit = true;
var as = tx.getActionSequence();
var len = as.length;
for (var i = 0;i < len;i++) {
var node = as[i];
if ((node.type === "call" || node.type === "construct") && (JAM.identical(node.value, _Location_prototype_reload) || JAM.identical(node.value, _Location_prototype_replace) || JAM.identical(node.value, _Location_prototype_assign) || JAM.identical(node.value, _HTMLFormElement_prototype_submit))) {
commit = false;
break;
}
if (node.type === "write" && (node.id === "location" && JAM.instanceof(node.obj, _Window) || true && JAM.instanceof(node.obj, _Location))) {
commit = false;
break;
}
}
if (commit) {
JAM.process(tx);
} else {
JAM.prevent(tx);
}
}
pFull.subsumedBy = pFull;
Object.freeze(pFull);
return {pFull:pFull};
}()
<file_sep>
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var _logger = Log4Moz.repository.getLogger("policyedit");
_logger.level = Log4Moz.Level["All"];
var needsSave = false;
function initField(fieldId, data) {
var polfield = document.getElementById(fieldId);
polfield.value = data;
polfield.disabled = false;
}
function saveFile(filename, data) {
let path = getLocalDirectory();
path.append(filename);
_logger.info('Saving file ' + path.path);
// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
var ostream = FileUtils.openSafeFileOutputStream(path);
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
_logger.error('Unable to save file: ' + path.path);
return;
}
// Data has been written to the file.
needsSave = false;
});
}
function loadFile(filename, fieldId) {
let path = getLocalDirectory();
path.append(filename);
_logger.info('Loading file ' + path.path);
if (path.exists()) {
NetUtil.asyncFetch(path, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
_logger.error('Unable to open policy file: ' + path.path);
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
initField(fieldId, data);
});
} else {
initField(fieldId, '');
}
}
function onChange() {
needsSave = true;
}
function onLoad() {
loadFile('policy.js', 'txtPolicy');
loadFile('libTx.js', 'txtLibrary');
}
function onSave() {
var poldata = document.getElementById('txtPolicy').value;
saveFile('policy.js', poldata);
var libdata = document.getElementById('txtLibrary').value;
saveFile('libTx.js', libdata);
}
function onClose() {
var ok = true;
if (needsSave) {
ok = window.confirm('Data has not been saved, really close?');
}
if (ok) window.close();
}
<file_sep>#!/bin/bash
projname=extension
projdir=~/cs/jam/$projname
#1 Specify the path where the chrome.manifest and install.rdf files live
# in the <EMAIL> file.
cat $projdir/doc/<EMAIL>
#2 Delete the non-local extension if it exists.
rm -f ~/.mozilla/firefox/qjsdmy6u.default-1422481910445/extensions/jam-extension@<EMAIL>.xpi
#3 Copy the test extension pointer file to the extensions dir.
cp $projdir/doc/jam-<EMAIL>@<EMAIL> ~/.mozilla/firefox/qjsdmy6u.default-1422481910445/extensions/
#4 Edit extensions.cache and remove any references to the app ID.
#sed -i '/<EMAIL>/ d' ~/.mozilla/firefox/qjsdmy6u.default-1422481910445/extensions.cache
#5 Restart Firefox.
| 4798305a13f3a025dd0dd175ee8dfbb61f84e258 | [
"JavaScript",
"Shell"
] | 5 | JavaScript | blackoutjack/jamextension | efccaca0ef953da3aab12d5fcac2d4ee8be81d57 | a50d548d60d1eb97773ed9d2156d7e7f376a8b76 |
refs/heads/master | <file_sep>const dbconfig = require("../dbconfig.js")
const mysql = require('mysql')
function loginService(usuario) {
return new Promise(function(resolve, reject) {
const sql = ' SELECT * FROM usuarios WHERE email ='+ mysql.escape(usuario.email) +' AND senha ='+ mysql.escape(usuario.senha);
dbconfig.conexao.query(sql, function (err, result, fields) {
console.log(sql)
if (err) throw reject(err);
console.log(err)
return resolve(JSON.parse(JSON.stringify(result)));
});
})
}
module.exports = {
loginService,
}<file_sep>import ApiService from './ApiService'
class RegistrarUsuarioService {
static registrarUsuario(nome, email, senha) {
return ApiService.registrarUsuario(nome, email, senha)
}
}
export default RegistrarUsuarioService
<file_sep>module.exports = class Reserva{
constructor(id, id_sala, id_usuario, data_inicial, data_final, descricao){
this.id = id
this.id_sala = id_sala
this.id_usuario = id_usuario
this.data_inicial = data_inicial
this.data_final = data_final
this.descricao = descricao
}
}<file_sep>const login = require('../service/usuarioService/loginService')
const cadastrarUsuario = require('../service/usuarioService/cadastrarUsuarioService')
const authService = require('../service/authService/authService')
exports.login = (req, res, next) => {
const usuario = req.body
login.loginService(usuario)
.then((usuario) => {
console.log(usuario.email)
const token = authService.getToken(usuario[0].email, usuario[0].id)
if (usuario.length <= 0) {
res.status(404).send("Email ou senha incorretos");
}
res.status(200).send({token});
})
.catch(() => {
res.status(404).send("Email ou senha incorretos");
})
};
exports.registrar = (req, res) => {
const usuario = req.body
cadastrarUsuario.cadastrarUsuarioService(usuario)
res.status(201).send(usuario);
};
<file_sep>const dbconfig = require("../dbconfig.js")
const mysql = require('mysql')
function getSalasDisponiveisService(reserva) {
return new Promise(function(resolve, reject) {
// let sql = 'SELECT * FROM salas WHERE id NOT IN ('
// sql += 'SELECT salas.id FROM salas LEFT JOIN reservas ON reservas.id_sala = salas.id';
// sql += ' WHERE reservas.data_inicial BETWEEN ' + formatDateTime(reserva.data, reserva.horaInicial);
// sql += ' AND ' + formatDateTime(reserva.data, reserva.horaFinal);
// sql += ' OR reservas.data_final BETWEEN '+ formatDateTime(reserva.data, reserva.horaInicial);
// sql += ' AND ' + formatDateTime(reserva.data, reserva.horaFinal);
// sql += 'OR '+ formatDateTime(reserva.data, reserva.horaInicial);
// sql += ' BETWEEN reservas.data_inicial AND reservas.data_final';
// sql += ' OR '+ formatDateTime(reserva.data, reserva.horaFinal);
// sql += ' BETWEEN reservas.data_inicial AND reservas.data_final)';
let sql = 'SELECT * FROM salas WHERE id NOT IN ('
sql += 'SELECT salas.id FROM salas LEFT JOIN reservas ON reservas.id_sala = salas.id';
sql += ' WHERE reservas.data_inicial >= ' + formatDateTime(reserva.data, reserva.horaInicial);
sql += ' AND reservas.data_inicial <=' + formatDateTime(reserva.data, reserva.horaFinal);
sql += ' OR reservas.data_final >= '+ formatDateTime(reserva.data, reserva.horaInicial);
sql += ' AND reservas.data_final <=' + formatDateTime(reserva.data, reserva.horaFinal);
sql += ' OR '+ formatDateTime(reserva.data, reserva.horaInicial);
sql += ' >= reservas.data_inicial ';
sql += ' AND '+ formatDateTime(reserva.data, reserva.horaInicial);
sql += ' <= reservas.data_final';
sql += ' OR '+ formatDateTime(reserva.data, reserva.horaFinal);
sql += ' >= reservas.data_inicial ';
sql += ' AND '+ formatDateTime(reserva.data, reserva.horaFinal);
sql += ' <= reservas.data_final )';
console.log(sql)
dbconfig.conexao.query(sql, function (err, result, fields) {
if (err) return reject(err);
return resolve(JSON.parse(JSON.stringify(result)));
});
})
}
function formatDateTime(date, time) {
return mysql.escape(date + ' ' + time)
}
module.exports = {
getSalasDisponiveisService,
}<file_sep>module.exports = class Sala{
constructor(id, nome, descricao){
this.id = id
this.nome = nome
this.descricao = descricao
}
}<file_sep>import React, { Component, Fragment } from "react";
import { Redirect } from "react-router-dom";
import { Button, Input, Table } from "reactstrap";
import Select from "../../components/generic/Select/index";
import Header from "../../components/Header/index";
import CardSala from "../../components/CardSala/index";
import "./style.css";
import GetSalasDisponiveisService from "../../services/GetSalasDisponiveisService";
import CadastrarReservaService from "../../services/CadastrarReservaService";
import GetReservasService from "../../services/GetReservasService";
import moment from "moment";
import jwt from 'jsonwebtoken'
export default class Reserva extends Component {
constructor(props) {
super(props);
this.state = {
shouldRedirectLogin: false,
data: "",
horaInicial: "",
horaFinal: "",
sala: "",
descricao: "",
validateDataInicial: "",
valiadteDataFinal: "",
salas: [],
reservas: [],
filter: "Próximas reservas",
};
this.handleChange = this.handleChange.bind(this)
}
componentDidMount() {
this.getReservas();
}
getReservas() {
GetReservasService.getReservas()
.then(result => {
this.setState({
reservas: result.data
});
console.log(result.data);
})
.catch(err => { });
}
getSalas = () => {
if (this.verifyDateCompleted()) {
const reserva = this.state;
console.log(reserva);
GetSalasDisponiveisService.getSalasDisponiveis(
reserva.data,
reserva.horaInicial,
reserva.horaFinal
)
.then(result => {
this.setState({
salas: this.mapSalas(result.data)
});
})
.catch(err => { });
}
};
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
})
}
verifyDateCompleted() {
const reserva = this.state;
return (
reserva.data.length === 10 &&
reserva.horaInicial.length === 5 &&
reserva.horaFinal.length === 5
);
}
validateDate() { }
getCategoriesOptions() {
return [
{
value: "",
text: "Nenhuma sala selecionada"
}
].concat(
this.state.salas.map(sala => {
return {
value: sala.id,
text: sala.nome
};
})
);
}
goCadastrarReserva = () => {
const reserva = this.state;
console.log(reserva);
if (
reserva.data === "" ||
reserva.horaInicial === "" ||
reserva.horaFinal === "" ||
reserva.sala === "" ||
reserva.descricao === ""
) {
return;
}
const token = localStorage.getItem("accessToken");
const decoded = jwt.decode(token, { complete: true });
const id = decoded.payload.id
CadastrarReservaService.cadastrarReserva(
reserva.sala,
id,
reserva.data,
reserva.horaInicial,
reserva.horaFinal,
reserva.descricao
)
.then(result => {
this.setState({
sala: "",
data: "",
horaInicial: "",
horaFinal: "",
descricao: "",
salas: []
});
})
.catch(err => { });
this.getReservas();
};
selectSala = id => {
const salas = this.state.salas.map(sala => {
return {
...sala,
selected: sala.id === id
};
});
this.setState({
salas,
sala: id
});
};
mapSalas = salas => {
return salas.map(sala => {
return {
...sala,
selected: false
};
});
};
renderSalas() {
return (
<div className="container-salas-disponiveis">
{this.state.salas.map(sala => {
return (
<CardSala
id={sala.id}
titulo={sala.nome}
descricao={sala.descricao}
selectSala={this.selectSala}
selected={sala.selected}
/>
);
})}
</div>
);
}
renderForm() {
return (
<div className="container-form">
<span>Data</span>
<Input
value={this.state.data}
name="data"
onChange={this.handleChange}
type="date"
/>
<span>Hora inicial</span>
<Input
value={this.state.horaInicial}
name="horaInicial"
onChange={this.handleChange}
type="time"
/>
<span>Hora final</span>
<Input
value={this.state.horaFinal}
name="horaFinal"
onChange={this.handleChange}
type="time"
/>
<Button
className="button-save-sala"
color="secundary"
onClick={this.getSalas}
>
Buscar
</Button>
<span>Descrição da reserva</span>
<Input
value={this.state.descricao}
name="descricao"
onChange={this.handleChange}
type="textarea"
/>
<Button
className="button-save-sala"
color="secundary"
onClick={this.goCadastrarReserva}
>
Cadastrar
</Button>
</div>
);
}
formatDate = date => {
return moment(date.split('.')[0], "YYYY-MM-DD hh:mm:ss").subtract(3, 'hours').format("DD/MM/YYYY HH:mm");
};
getReservasMapeadas = () => {
const { reservas, filter } = this.state
const reservasMap = reservas.map(reserva => {
return {
...reserva,
data: this.formatDate(reserva.data_inicial).split(' ')[0],
hora_inicial: this.formatDate(reserva.data_inicial).split(' ')[1],
hora_final: this.formatDate(reserva.data_final).split(' ')[1],
data_final: this.formatDate(reserva.data_final),
ano: moment(reserva.data_final).year()
}
})
return filter === "Próximas reservas" ? reservasMap : reservasMap.reverse()
}
renderReservas() {
const { filter } = this.state
const data = filter === "Próximas reservas" ? moment(new Date().getTime()).format("DD/MM/YYYY HH:mm") : ''
return (
<tbody>
{this.getReservasMapeadas().filter(r => r.data_final > data || r.ano > moment(new Date().getTime()).year())
.map(reserva => {
return (
<tr>
<td className="sala-coluna">{reserva.descricao}</td>
<td className="sala-coluna">
{reserva.data}
</td>
<td className="sala-coluna">
{reserva.hora_inicial}
</td>
<td className="sala-coluna">
{reserva.hora_final}
</td>
<td className="sala-coluna">{reserva.usuario}</td>
<td className="sala-coluna">{reserva.sala}</td>
</tr>
)
})
}
</tbody>
);
}
render() {
return (
<div>
<Header disabledReserva={true} />
<h1>Reserve uma sala</h1>
<div className="container-reserva">
{this.renderForm()}
<div className="tabela-reservas">
<Select
options={[{ value: "Próximas reservas", text: "Próximas reservas" }, { value: "Histórico de reservas", text: "Histórico de reservas" }]}
name="filter"
handleChange={this.handleChange}
/>
<Table striped>
<thead>
<tr className="sala-coluna">
<th className="sala-coluna">Descrição da reserva</th>
<th className="sala-coluna">Data</th>
<th className="sala-coluna">Hora inicial</th>
<th className="sala-coluna">Hora final</th>
<th className="sala-coluna">Usuário</th>
<th className="sala-coluna">Sala</th>
</tr>
</thead>
{this.renderReservas()}
</Table>
</div>
</div>
{this.renderSalas()}
</div>
);
}
}
<file_sep>export default {
API_URL_BASE: 'http://localhost:4040'
}
<file_sep>import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import { Button } from "reactstrap";
import Header from "../../components/Header/index";
import "./style.css";
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
shouldRedirectLogin: false,
dataInicial: "",
dataFinal: "",
validateDataInicial: "",
valiadteDataFinal: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
_logout = () => {
localStorage.removeItem('accessToken')
this.setState({
shouldRedirectLogin: true
});
};
validateDate() {}
getCategoriesOptions() {
return [
{
value: "Sala de reunião",
text: "Sala de reunião"
},
{
value: "Sala 102",
text: "Sala 102"
},
{
value: "Sala 103",
text: "Sala 103"
}
];
}
render() {
if (this.state.shouldRedirectLogin) {
return <Redirect to="/login" />;
}
return (
<div className="container-home">
<Header disabledHome={true} />
<div className="content-home">
<h1>RESERVA DE SALAS</h1>
<span onClick={this._logout}>Logout</span>
</div>
<div className="content-home-secondary" />
</div>
);
}
}
<file_sep>import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import { Row, Input, Button } from "reactstrap";
import LoginService from "../../services/LoginService";
import "./style.css";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
shouldRedirectHome: false,
shouldRedirectRegistrar: false,
email: '',
senha: '',
error: false,
};
this.handleChange = this.handleChange.bind(this);
}
_login = () => {
this.setState({
shouldRedirectHome: true
});
};
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
_onClickLoginButton = () => {
const account = this.state
if (!account.email || !account.senha) {
return
}
LoginService.login(account.email, account.senha)
.then(result => {
localStorage.setItem("accessToken", result.data.token);
this.setState({
shouldRedirectHome: true,
error: false
});
})
.catch(err => {
this.setState({
error: true
});
});
};
_registrar = () => {
this.setState({
shouldRedirectRegistrar: true
});
};
render() {
if (this.state.shouldRedirectHome) {
return <Redirect to="/home" />;
} else if (this.state.shouldRedirectRegistrar) {
return <Redirect to="/registrar" />;
}
return (
<div className="container-login">
<div className="form-login">
<h1>Reserva de salas</h1>
{this.state.error && (
<span className="alert">Email ou senha incorretos</span>
)}
<Input
label="E-mail"
value={this.state.email}
name="email"
placeholder="Digite seu e-mail"
onChange={this.handleChange}
type="email"
/>
<Input
value={this.state.senha}
name="senha"
placeholder="Digite sua senha"
onChange={this.handleChange}
type="password"
/>
<Button color="secundary" onClick={this._onClickLoginButton}>
Login
</Button>
<span className="link" onClick={this._registrar}>
Cadastre-se
</span>
</div>
</div>
);
}
}
<file_sep>import ApiService from './ApiService'
class GetReservasService {
static getReservas() {
return ApiService.getReservas()
}
}
export default GetReservasService
<file_sep>import CONFIG from '../config'
import axios from 'axios'
const token = localStorage.getItem('accessToken')
const configHeader = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'x-access-token': token ? token : ''
}
};
class ApiService {
static login(email, senha) {
return axios.post(`${CONFIG.API_URL_BASE}/usuario/login`, {
email,
senha,
}, configHeader)
}
static registrarUsuario(nome, email, senha) {
return axios.post(`${CONFIG.API_URL_BASE}/usuario/registrar`, {
nome,
email,
senha
}, configHeader)
}
static getSalas() {
return axios.get(`${CONFIG.API_URL_BASE}/salas/`, configHeader)
}
static getSalasDisponiveis(data, horaInicial, horaFinal) {
return axios.post(`${CONFIG.API_URL_BASE}/salas/disponiveis`, {
data,
horaInicial,
horaFinal,
}, configHeader)
}
static cadastrarAlterarSala(id, nome, descricao) {
if (id) {
return axios.put(`${CONFIG.API_URL_BASE}/salas/editar`, {
id,
nome,
descricao,
}, configHeader)
}
return axios.post(`${CONFIG.API_URL_BASE}/salas/cadastrar`, {
nome,
descricao
}, configHeader)
}
static deletarSala(id) {
return axios.delete(`${CONFIG.API_URL_BASE}/salas/deletar/${id}`, configHeader)
}
static cadastrarReserva(idSala, idUsuario, data, horaInicial, horaFinal, descricao) {
return axios.post(`${CONFIG.API_URL_BASE}/reservas/cadastrar`, {
idSala,
idUsuario,
data,
horaInicial,
horaFinal,
descricao
}, configHeader)
}
static getReservas() {
return axios.get(`${CONFIG.API_URL_BASE}/reservas/`, configHeader)
}
}
export default ApiService
<file_sep>import React from 'react'
import './style.css'
export default class extends React.Component {
constructor(props) {
super(props)
}
cardSelected() {
return this.props.selected ? "card text-white bg-dark mb-3" : "card bg-light mb-3"
}
render() {
const { id } = this.props
return (
<div className={`container-card-sala ${this.cardSelected()}`} onClick={() => this.props.selectSala(id)}>
<div className="card-header"><b>{this.props.titulo}</b></div>
<div className="card-body">
{/* <h5 className="card-title">Light card title</h5> */}
<p className="card-text">
{this.props.descricao}
</p>
</div>
</div>
)
}
}<file_sep>const express = require('express');
const router = express.Router();
const controller = require('../controller/salasController')
const authService = require('../service/authService/authService')
router.get('/', authService.verifyToken, controller.get);
router.post('/cadastrar', controller.post);
router.post('/disponiveis', controller.getSalasDisponiveis);
router.put('/editar', controller.put);
router.delete('/deletar/:id', controller.delete);
module.exports = router;<file_sep>import ApiService from './ApiService'
class GetSalasService {
static getSalas() {
return ApiService.getSalas()
}
}
export default GetSalasService
<file_sep>const dbconfig = require("../dbconfig.js")
const mysql = require('mysql')
function cadastrarReservaService(reserva) {
let sql = 'INSERT INTO reservas (id_sala, id_usuario, data_inicial, data_final, descricao)'
sql += 'VALUES (' + reserva.idSala + ',' + reserva.idUsuario + ','
sql += formatDateTime(reserva.data, reserva.horaInicial) + ','
sql += formatDateTime(reserva.data, reserva.horaFinal) + ','
sql += mysql.escape(reserva.descricao) + ')';
console.log('SQL: ' + sql)
dbconfig.conexao.query(sql, function (err, result) {
// if (err) throw err;
if (err) console.log(err)
});
}
function formatDateTime(date, time) {
return mysql.escape(date + 'T' + time)
}
module.exports = {
cadastrarReservaService,
}<file_sep>const express = require('express');
const app = express();
const router = express.Router();
const bodyParser = require('body-parser');
const cors = require('cors');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
const index = require('./routes/index');
const usuarioRoute = require('./routes/usuarioRoute');
const salasRoute = require('./routes/salasRoute');
const reservaRoute = require('./routes/reservaRoute');
app.use('/', index);
app.use('/usuario', usuarioRoute);
app.use('/salas', salasRoute);
app.use('/reservas', reservaRoute);
module.exports = app;
<file_sep>import ApiService from './ApiService'
class CadastrarAlterarProdutoService {
static cadastrarAlterarSala(id, nome, descricao) {
return ApiService.cadastrarAlterarSala(id, nome, descricao)
}
}
export default CadastrarAlterarProdutoService
<file_sep>const cadastrarReserva = require('../service/reservaService/cadastrarReservaService')
const getReservasOrdenadasPorDataDesc = require('../service/reservaService/getReservasOrdenadasPorDataDesc')
exports.get = (req, res, next) => {
getReservasOrdenadasPorDataDesc.getReservas()
.then((reservas) => {
res.status(200).send(reservas);
})
};
exports.post = (req, res, next) => {
let reserva = req.body
cadastrarReserva.cadastrarReservaService(reserva)
res.status(200).send(reserva);
};
<file_sep>const getSalas = require('../service/salaService/getSalasService')
const getSalasDisponiveis = require('../service/salaService/getSalasDisponiveisService')
const cadastrarSala = require('../service/salaService/cadastrarSalaService')
const editarSala = require('../service/salaService/editarSalaService')
const deletarSala = require('../service/salaService/deleteSalaService')
exports.get = (req, res, next) => {
getSalas.getSalasService()
.then((salas) => {
console.log(salas)
res.status(200).send(salas);
})
};
exports.getSalasDisponiveis = (req, res, next) => {
let reserva = req.body
getSalasDisponiveis.getSalasDisponiveisService(reserva)
.then((salas) => {
console.log(salas)
res.status(200).send(salas);
})
};
exports.post = (req, res, next) => {
let sala = req.body
console.log(sala)
cadastrarSala.cadastrarSalaService(sala)
res.status(200).send(sala);
};
exports.put = (req, res, next) => {
let sala = req.body
editarSala.editarSalaService(sala)
res.status(200).send(sala);
};
exports.delete = (req, res, next) => {
let id = req.params.id;
deletarSala.deleteSalaService(id)
res.status(200).send();
};<file_sep>const express = require('express');
const router = express.Router();
router.get('/teste/:user', function (req, res, next) {
let user = req.params.user
res.status(200).send({
title: "Teste",
text: "texto texto texto texto texto texto texto texto texto texto texto ",
user
});
});
module.exports = router;<file_sep>import ApiService from './ApiService'
class DeletarSalaService {
static deletarSala(id) {
return ApiService.deletarSala(id)
}
}
export default DeletarSalaService<file_sep>import React, { Component } from 'react';
import { Switch, Route, Redirect, Link } from 'react-router-dom'
import './App.css';
import axios from 'axios'
import Loading from './components/generic/Loading/index'
import Home from './scenes/Home/index'
import Login from './scenes/Login/index'
import Reserva from './scenes/Reserva/index'
import Salas from './scenes/Salas/index'
import Registrar from './scenes/Registrar/index'
class App extends Component {
constructor() {
super()
this.axiosConfig()
this.state = {
loading: false
};
this.token = localStorage.getItem('accessToken')
}
axiosConfig() {
const self = this
axios.interceptors.request.use((config) => {
self.toggleLoading()
return config
});
axios.interceptors.response.use((response) => {
self.toggleLoading()
return response;
}, (error) => {
self.toggleLoading()
return Promise.reject(error)
})
}
toggleLoading() {
this.setState({
loading: !this.state.loading
});
}
render() {
return (
<div className="App">
{this.state.loading && <Loading />}
{!this.token && <Redirect to="/login" />}
<Switch>
<Route exact path="/home" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/registrar" component={Registrar} />
<Route exact path="/reserva" component={Reserva} />
<Route exact path="/salas" component={Salas} />
{this.token ? <Redirect to="/home" /> : <Redirect to="/login" />}
</Switch>
</div>
);
}
}
export default App;
<file_sep>const dbconfig = require("../dbconfig.js")
const mysql = require('mysql')
function editarSalaService(sala) {
const sql = 'update salas set nome ='+ mysql.escape(sala.nome) +','+
'descricao ='+ mysql.escape(sala.descricao) +
'where id ='+ sala.id ;
dbconfig.conexao.query(sql, function (err, result) {
// if (err) throw err;
if (err) console.log(err)
});
}
module.exports = {
editarSalaService,
}<file_sep>const express = require('express');
const router = express.Router();
const controller = require('../controller/usuarioController')
router.post('/registrar',controller.registrar);
router.post('/login',controller.login);
module.exports = router;<file_sep>const dbconfig = require("../dbconfig.js")
function deleteSalaService(id) {
const sql = 'delete from salas where id =' + id;
dbconfig.conexao.query(sql, function (err, result) {
// if (err) throw err;
if (err) console.log(err)
});
}
module.exports = {
deleteSalaService,
} | 8562ba1c45caa174ff6d398e719144a19a31570b | [
"JavaScript"
] | 26 | JavaScript | luanwinck/Reserva-de-salas | 336f978f151e7c4ff41f14d603427bebf4112db1 | ce5ccd7594bb9ddabd8517f851315b747e9a7554 |
refs/heads/master | <repo_name>tolewicz/python_practice<file_sep>/netflixto.py
#modules
import csv
import os
#prompt video you want to watch
movie_title = input('what movie do you want to wtch ? \n')
#initially status of the movie, if cahnges to True, movies is on netflix
movie_status = False
#provide path to file with movies
csvpath = os.path.join('Resources','netflix_ratings.csv')
print(csvpath)
#open cv file, opening file only but not reading yet
with open(csvpath, newline='',) as csvfile:
movie_reader = csv.reader(csvfile, delimiter=',' )
#this step is responsible for reading the file LINE BY LINE as a set of lists with each word indexed!
for row in movie_reader:
#row[0] means 1st word in the list of row that is read
# "if" goes line by line
if row[0] == movie_title:
print(f'{row[0]} is rated {row[1]} with a ratings {row[0]}')
#if the movie is in line that is red we print statement, change status (no efect for this loop) and break
movie_status = True
break
#if the movie is not i the line we keep cycling until find it
#after finishing cycling we leave the loop and check the status of the movie
#if the status of the movie was changed to "True" the next statement shouldn't be executed,
#if the status of the movie was NOT changed and remains "False" the next test will post a message
if movie_status == False:
print(f"we don't have '{movie_title}'")
<file_sep>/README.md
# Searching Netflix movie
## Project overview
Utilizing Python program to search movie and its rating in Netflex data base saved .csv document.
The program prompts user to provide title then it opens the txt file and search for the title.
If the title is present the movie title and its rating is displayed. Otherwise message "We don’t have {movie title}" is displayed
## Resources
- Python 3
- netflixto.py
- netflix_ratings.csv
| fc6e607486a2b0bbac716f5de6c48cfbe44ad8cf | [
"Markdown",
"Python"
] | 2 | Python | tolewicz/python_practice | 8cb4ecb34d92ddc61171213de1d71e2a61ec990c | 45e9f558d77f40ace15090c65924db235a9afa67 |
refs/heads/master | <file_sep>module.exports = {
list: function (req, res) {
return res.end(JSON.stringify([
{
name: "Banana",
},
{
name: "Apple",
},
{
name: "Orange",
}
]));
}
}; | b606b0e4efc3b280ece87ab6c0fe5365c6a0f678 | [
"JavaScript"
] | 1 | JavaScript | mageddo/nodejs-sails-angular-ng-table | ff15ba0d1583627bfb419775f69f0920e37adedc | cbe3817502fbdcfa1256110629a7326c6097b827 |
refs/heads/master | <file_sep>from global_config import PASSWD,NAME
class_course_table_url = "http://192.168.3.11/jwglxt/kbdy/bjkbdy_cxBjKb.html?gnmkdm=N214505"
pre_class_course_table_url = "http://192.168.3.11/jwglxt/kbdy/bjkbdy_cxBjkbdyTjkbList.html?gnmkdm=N214505"
<file_sep>from global_config import *
public_key_url = "http://192.168.127.129/jwglxt/xtgl/login_getPublicKey.html"
index_url = "http://192.168.3.11/jwglxt/xtgl/login_slogin.html"
test_url = "http://192.168.3.11/jwglxt/xtgl/index_cxBczjsygnmk.html"
<file_sep>from flask import Blueprint
api = Blueprint('get_exam_api', __name__)
from .get_exam import *<file_sep>from flask import Blueprint
api = Blueprint('message_push_api', __name__)
from .message_push import *<file_sep>from global_config import proxies
url1 = "https://fee.icbc.com.cn/index.jsp"
url2 = "https://fee.icbc.com.cn/servlet/ICBCINBSEstablishSessionServlet"
post_data = {
"pageMark": "3",
"paymentContent": "busiCode=",
"queryPageinfo": "1",
"netType": "181",
"IEVersionFlag": "ANDROID-CHROME-0",
"ComputID": "98",
"PlatFlag": "8",
"areaCodeTmp": "0502",
"areaNameTmp": "̫ԭ",
"dse_menuid": "PM002",
"IN_PAYITEMCODE": "PJ120012021000010048",
"cmd": "",
"isShortpay": "",
"maskFlag": "0",
"isP3bank": "0"
}
<file_sep>import json
import re
import bs4
from flask import Response
from flask import request
from plugins._login_PhyEws.login_PhyEws import login_PhyEws
from . import api
from .config import PhyEws_grade_url
@api.route('/GetPhyEwsGrade', methods=['GET'])
def handle_get_PhyEws_grade():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
res = get_PhyEws_grade(name, passwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_PhyEws_grade(name, passwd):
message = "OK"
error = ""
code = 0
data = []
if len(name) < 1 or len(passwd) < 1:
code = -2
message = "登陆失败"
error = "账号密码不能为空"
else:
session = login_PhyEws(name, passwd)
r = session.get(PhyEws_grade_url)
html = r.content.decode("gbk")
soup = bs4.BeautifulSoup(html, "html.parser")
tds = soup.find_all(class_="forumRow")
length = len(tds)
i = 0
c = 0
g = 0
rgx = re.compile(u'[((](.*)[))]')
while i < length:
grade = {"Course_Name": rgx.sub('', tds[i + 1].string),
u"Course_Grade": tds[i + 7].string}
data.append(grade)
if tds[i + 7].string.isdigit():
c += 1
g += int(tds[i + 7].string)
i += 8
if g != 0:
data.append({"Course_Name": "平均分",
u"Course_Grade": round(1.0 * g / c, 2)})
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>import json
from flask import Response
from flask import request
from utils.sql_helper import SQLHelper
from . import api
@api.route('/GetIdleClassroom', methods=['GET'])
def handle_get_idle_classroom():
building = request.args.get('building', "")
class_with_week = request.args.get('class', "")
week = request.args.get('week', "")
res = get_idle_classroom_list(building, class_with_week, week)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/GetBuildingList', methods=['GET'])
def handle_get_building_list():
res = get_building_list()
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_building_list():
message = "OK"
error = ""
code = 0
data = [u"一号楼", u"四号楼", u"六号楼", u"七号楼", u"八号楼", u"九号楼", u"十号楼", u"十一号楼", u"十四号楼", u"十五号楼",
u"十六号楼", u"旧一号楼", u"语音", u"其他"]
return {"message": message, "error": error, "code": code, "data": data}
def get_idle_classroom_list(building, class_with_week, week):
message = "OK"
error = ""
code = 0
data = []
if str.isdigit(week[1:]) and int(week[1:]) <= 20:
args = (building, class_with_week, week)
sql = "select * from idle_classroom where building = '%s' and class_with_week = '%s' and `%s` = 1" % args
results = SQLHelper.fetch_all(sql)
for row in results:
data.append(row[2])
# TODO 若重新启用,把上面改为列名
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>from flask import Response
from flask import request
from plugins_v2._login_v2.login_v2 import login
from . import api
from .config import *
@api.route('/GetCourseTable', methods=['GET'])
def handle_get_course_table():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
res = get_course_table(name, passwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_course_table(name, passwd):
message = "OK"
code = 0
data = []
if len(name) < 1 or len(passwd) < 1:
code = -2
message = "账号密码不能为空"
else:
session = login(name, passwd)
if isinstance(session, str):
code = -3
message = session
else:
post_data = {
"xnm": 2019,
"xqm": 12
}
course_table = session.post(course_table_url, data=post_data).json()
tables = []
cnt = 0
name_dict = {}
for index, table in enumerate(course_table["kbList"]):
spited = table["jcor"].split("-")
if table["kcmc"] not in name_dict:
name_dict[table["kcmc"]] = cnt
cnt += 1
tables.append({
"Course_Number": table["kch_id"],
"Course_Name": table["kcmc"],
"Course_Credit": table["xf"],
"Course_Test_Type": table["khfsmc"],
"Course_Teacher": table["xm"],
"Course_Week": table["zcd"],
"Course_Color": name_dict[table["kcmc"]],
"Course_Time": table["xqj"],
"Course_Start": spited[0],
"Course_Length": int(spited[1]) - int(spited[0]) + 1,
"Course_Building": table["xqmc"],
"Course_Classroom": table["cdmc"]
})
for d in course_table["sjkList"]:
tables.append({
"Course_Name": d["sjkcgs"]
})
data = tables
return {"message": message, "code": code, "data": data}
<file_sep>from flask import Blueprint
api = Blueprint('get_PhyEws_grade_api', __name__)
from .get_PhyEws_grade import *
<file_sep>from flask import Blueprint
# TODO 兼容现存客户端,客户端更新后可取消注释
# api = Blueprint('get_course_table_api_v2', __name__, url_prefix="/v2")
api = Blueprint('get_class_course_table_api', __name__)
from .get_class_course_table_v2 import *
<file_sep>from flask import Blueprint
api = Blueprint('get_grade_api_v2', __name__, url_prefix="/v2")
from .get_grade_v2 import *
<file_sep>from flask import Blueprint
# api = Blueprint('get_course_api_v2', __name__, url_prefix="/v2")
# TODO 兼容现有版本
api = Blueprint('get_course_api_v2', __name__)
from .get_course_v2 import *
<file_sep>import pprint
import time
import traceback
import pymysql
from global_config import NAME, PASSWD
from plugins_v2._login_v2.login_v2 import login
pp = pprint.PrettyPrinter(indent=2)
session = login(NAME, PASSWD)
course_db = pymysql.connect("127.0.0.1", "root", "", "course", charset='utf8mb4')
course_cursor = course_db.cursor()
if isinstance(session, str):
code = -3
message = session
else:
a = "19080741"
post_data = {
"xnm": "2019",
"xqm": "12",
"xqh_id": "01",
"njdm_id": "",
"jg_id": "",
"zyh_id": "",
"zyfx_id": "",
"bh_id": "",
"_search": "false",
"queryModel.showCount": "5000",
}
pre_data = session.post("http://172.16.58.3/jwglxt/kbdy/bjkbdy_cxBjkbdyTjkbList.html?gnmkdm=N214505",
data=post_data).json()
for item in pre_data["items"]:
post_data = {
"xnm": "2019",
"xqm": "12",
"xnmc": "2019-2020",
"xqmmc": "2",
"xqh_id": "01",
"njdm_id": item["njdm_id"],
"zyh_id": item["zyh_id"],
"bh_id": item["bh_id"],
"tjkbzdm": "1",
# "zymc": "物联网工程(2013)",
"tjkbzxsdm": "0",
"zxszjjs": True
}
course_table = session.post("http://222.31.49.139/jwglxt/kbdy/bjkbdy_cxBjKb.html?gnmkdm=N214505&su=1707004548",
data=post_data).json()
for item_j in course_table["kbList"]:
spited = item_j["jcor"].split("-")
sql = "INSERT IGNORE INTO course.`课程-2020-1`(`教学班编号`, `学院`, `课程名`, `教师`, `周次`, `星期`, `开始节次`, " \
"`时长节次`, `教学楼`, `教室`) " \
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
(item_j.get("jxb_id"),item.get("jgmc"), item_j.get("kcmc"), item_j.get("xm"), item_j.get("zcd"), item_j.get("xqj"),
spited[0], int(spited[1]) - int(spited[0]) + 1, item_j.get("xqmc"), item_j.get("cdmc"))
try:
course_cursor.execute(sql)
course_db.commit()
except:
traceback.print_exc()
course_db.rollback()
time.sleep(1)
<file_sep>import base64
import pickle
import re
import requests
import rsa
from global_config import proxies
from utils.redis_connections import redis_session
from .config import index_url, public_key_url, test_url
def base_64_to_int(raw_str: str) -> int:
return int.from_bytes(base64.b64decode(raw_str), 'big')
def login(name, passwd, disable_cache=False):
session = requests.session()
session.proxies = proxies
if not disable_cache:
cookies_decoded = redis_session.get("cookies" + name)
if cookies_decoded:
session.cookies = pickle.loads(cookies_decoded.encode('latin1'))
r = session.get(test_url, allow_redirects=False)
if r.status_code == 200:
redis_session.expire("cookies" + name, 3600)
return session
else:
redis_session.delete("cookies" + name)
index_html = session.get(index_url).content.decode()
csrf_token = re.search('name="csrftoken" value="(.*?)"', index_html).group(1)
public_key_dict = session.get(public_key_url).json()
public_key = rsa.PublicKey(base_64_to_int(public_key_dict["modulus"]), base_64_to_int(public_key_dict["exponent"]))
post_data = {
'csrftoken': csrf_token,
'yhm': name,
'mm': base64.b64encode(rsa.encrypt(passwd.encode(), public_key))
}
login_html = session.post(index_url, data=post_data).content.decode()
if login_html.find("不正确") != -1:
return "账号或密码错误"
else:
redis_session.set("cookies" + name, pickle.dumps(session.cookies).decode('latin1'), ex=3600)
return session
<file_sep>import datetime
import logging
import requests
from global_config import proxy_status_url, get_cookies_url
from utils.scheduler import scheduler
from utils.gol import global_values
def check_proxy():
try:
if requests.get(proxy_status_url).content.decode() == "ok":
global_values.set_value("proxy_status_ok", True)
vpn_cookies = requests.get(get_cookies_url).content.decode()
if not global_values.get_value("vpn_cookies"):
logging.info("已获取 VPN cookies:%s" % vpn_cookies)
global_values.set_value("vpn_cookies", vpn_cookies)
else:
global_values.set_value("proxy_status_ok", False)
logging.warning("代理离线")
except:
global_values.set_value("proxy_status_ok", True)
scheduler.add_job(check_proxy, 'interval', seconds=10, next_run_time=datetime.datetime.now())
<file_sep>from flask import Blueprint
api = Blueprint('card_balance_api', __name__)
from .balance import *
<file_sep>from global_config import *
<file_sep>import redis
from global_config import redis_password, redis_host, redis_port
redis_news = redis.StrictRedis(host=redis_host, port=redis_port, password=<PASSWORD>,
encoding='utf8', decode_responses=True, db=2)
redis_request_limit = redis.StrictRedis(host=redis_host, port=redis_port, password=<PASSWORD>,
encoding='utf8', decode_responses=True, db=3)
redis_token = redis.StrictRedis(host=redis_host, port=redis_port, password=<PASSWORD>,
encoding='utf8', decode_responses=True, db=4)
redis_session = redis.StrictRedis(host=redis_host, port=redis_port, password=<PASSWORD>,
encoding='utf8', decode_responses=True, db=0)
redis_cache = redis.StrictRedis(host=redis_host, port=redis_port, password=<PASSWORD>,
encoding='utf8', decode_responses=True, db=6)
<file_sep>from flask import Blueprint
api = Blueprint('search_library_api', __name__)
from .search_library import *
<file_sep>from flask import Blueprint
api = Blueprint('get_notice_v2', __name__, url_prefix="/v2/notice")
from .get_notice_v2 import *<file_sep>from global_config import *
grade_url = "http://192.168.3.11/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005"
<file_sep>from flask import Blueprint
api = Blueprint('to_ical_api', __name__)
from .to_ical import *<file_sep>import json
import logging
import traceback
import requests
from flask import Response
from flask import request
from . import api
@api.route('/MessagePush', methods=['POST'])
def handle_message_push():
data = request.json
res = message_push(data)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def message_push(data):
title = "小程序反馈更新了"
message = "但不知发生了什么"
try:
if "type" in data.keys():
if data["type"] == "post.created":
title = "%s%s发表了一个主贴" % (data["payload"]["post"]["nick_name"], data["payload"]["post"]["time"])
message = data["payload"]["post"]["content"]
elif data["type"] == "post.updated":
title = "%s%s发表的主贴已更新" % (data["payload"]["post"]["nick_name"], data["payload"]["post"]["time"])
message = data["payload"]["post"]["content"]
elif data["type"] == "reply.created":
title = "%s%s发表了一个回复" % (data["payload"]["reply"]["nick_name"], data["payload"]["reply"]["time"])
message = data["payload"]["reply"]["content"]
elif data["type"] == "reply.updated":
title = "%s%s发表的回复已更新" % (data["payload"]["reply"]["nick_name"], data["payload"]["reply"]["time"])
message = data["payload"]["reply"]["content"]
logging.info("反馈标题:%s" % title)
logging.info("反馈内容:%s" % message)
requests.post(
"https://api2.day.app:4443/ReNCULrNA3AxYFopZyKipB/%s/%s" % (
title.replace("/", "%2f"), message.replace("/", "%2f")))
logging.info("反馈信息推送成功")
except:
logging.error(traceback.format_exc())
logging.error("反馈信息推送失败")
return {}
<file_sep>import base64
import hashlib
import time
import requests
from Crypto.Cipher import AES
from flask import Response, request
from . import api
from .config import *
BS = AES.block_size # aes数据分组长度为128 bit
key = AES.new("76a9c9f0e5ae4d2d84bf6eda1613ddbf".encode(), AES.MODE_ECB)
def pad(m):
return (m + chr(16 - len(m) % 16) * (16 - len(m) % 16)).encode()
def sign(args: dict):
args["appId"] = "76a9c9f0e5ae4d2d84bf6eda1613ddbf"
args["appSecret"] = "<KEY>"
args_list = []
for k in sorted(args):
args_list.append(k + "=" + str(args[k]))
arg = "&".join(args_list)
del args["appId"]
del args["appSecret"]
return hashlib.md5(arg.encode("utf-8")).hexdigest()
@api.route('/captcha', methods=['GET'])
def handle_captcha():
res = captcha()
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/login', methods=['GET'])
def handle_login():
res = login(request.args)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/list', methods=['GET'])
def handle_list_grade():
student_id = request.args.get("id", "")
res = list_grade(student_id)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/detail', methods=['GET'])
def handle_grade_detail():
grade_id = request.args.get("id", "")
res = grade_detail(grade_id)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def grade_detail(grade_id):
message = "OK"
code = 0
data = ""
post_data = {
"meaScoreId": grade_id,
"timestamp": int(time.time() * 1000)
}
post_data["sign"] = sign(post_data)
res = requests.post(grade_detail_url, proxies=proxies, data=post_data).content.decode()
res_json = json.loads(res)
if res_json["returnCode"] == '200':
data = res_json["data"]
else:
message = res_json["returnMsg"]
code = -1
return {"message": message, "code": code, "data": data}
def list_grade(student_id):
message = "OK"
code = 0
data = ""
post_data = {
"userId": student_id,
"timestamp": int(time.time() * 1000)
}
post_data["sign"] = sign(post_data)
res = requests.post(grade_list_url, proxies=proxies, data=post_data).content.decode()
res_json = json.loads(res)
if res_json["returnCode"] == '200':
data = res_json["data"]
else:
message = res_json["returnMsg"]
code = -1
return {"message": message, "code": code, "data": data}
def captcha():
message = "OK"
code = 0
captcha_request = requests.get(captcha_code_url, proxies=proxies)
data = {
"captchaBase64": base64.b64encode(captcha_request.content).decode(),
"JSESSIONID": captcha_request.cookies.get("JSESSIONID")
}
return {"message": message, "code": code, "data": data}
def login(args):
message = "OK"
code = 0
data = {}
if len(args.get("name")) < 1 or len(args.get("passwd")) < 1:
code = -2
message = "账号密码不能为空"
else:
session = requests.session()
session.proxies = proxies
session.cookies.set("JSESSIONID", args.get("JSESSIONID"))
post_data = {
"uname": base64.b64encode(key.encrypt(pad(args.get("name")))).decode(),
"pwd": base64.b64encode(key.encrypt(pad(args.get("passwd")))).decode(),
"code": args.get("captcha"),
"timestamp": int(time.time() * 1000)
}
post_data["sign"] = sign(post_data)
login_res = json.loads(session.post(login_url, data=post_data, allow_redirects=False).content.decode())
if login_res["returnMsg"]:
code = 1
message = login_res["returnMsg"]
else:
info_res = json.loads(session.post(info_url).content.decode())
data = {
"id": info_res["data"][0]["sysUser"]["id"]
}
return {"message": message, "code": code, "data": data}
<file_sep>from global_config import mysql_host, mysql_password, mysql_user
import pymysql
classroom_db = pymysql.connect(mysql_host, mysql_user, mysql_password, "classroom", charset='utf8')
classroom_cursor = classroom_db.cursor()
course_db = pymysql.connect(mysql_host, mysql_user, mysql_password, "course", charset='utf8')
course_cursor = course_db.cursor()
exam_db = pymysql.connect(mysql_host, mysql_user, mysql_password, "exam", charset='utf8')
exam_cursor = exam_db.cursor()
notice_db = pymysql.connect(mysql_host, mysql_user, mysql_password, "notices", charset='utf8')
notice_cursor = notice_db.cursor()<file_sep>from flask import Blueprint
api = Blueprint('physical_fitness_test_api', __name__)
from .physical_fitness_test import *
<file_sep># coding=utf-8
import json
from flask import Response
from flask import request
from plugins_v2._login_v2.login_v2 import login
from . import api
@api.route('/Login', methods=['GET'])
def handle_login():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
res = login_(name, passwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def login_(name, passwd):
message = "登录成功"
code = 0
data = "0"
if len(name) < 1 or len(passwd) < 1:
code = -3
message = "账号密码不能为空"
if name.strip() != name:
code = -3
message = "用户名包含空字符"
else:
session = login(name, passwd, True)
if isinstance(session, str):
code = -3
message = session
return {"message": message, "code": code, "data": data}
<file_sep>import gevent.monkey
gevent.monkey.patch_all()
import time
from global_config import guest_data, appSecret, dont_cache_url, stopped_list, need_proxy_url, no_limit_url
from startup import load_task, load_plugin
from utils.scheduler import scheduler
from pywsgi import WSGIServer
from os import path
from flask import Flask, redirect, request, Response, g
import hashlib
import traceback
import flask_compress
from urllib.parse import unquote, quote
import json
from utils.redis_connections import redis_request_limit, redis_cache
from utils.logger import root_logger
import logging
from utils.gol import global_values
app = Flask(__name__)
flask_compress.Compress(app)
@app.errorhandler(404)
def page_not_found(e):
app.logger.warning("由于 404 重定向 %s", request.url)
return redirect('https://dreace.top')
@app.errorhandler(Exception)
def on_sever_error(e):
logging.exception(traceback.format_exc())
message = "服务器错误"
error = "未知错误"
code = -1
data = ""
resp = Response(json.dumps({"message": message, "error": error, "code": code, "data": data}),
mimetype='application/json')
return resp
@app.before_request
def a():
g.request_start_time = time.time()
@app.before_request
def check_auth():
message = "OK"
error = ""
code = 0
data = ""
if request.path == '/':
return redirect("https://dreace.top")
if request.path[1:] in stopped_list:
logging.warning("未开放查询")
message = "未开放查询"
code = -4
resp = Response(json.dumps({"message": message, "error": error, "code": code, "data": data}),
mimetype='application/json')
return resp
name = request.args.get('name', "")
args = dict(request.args)
if request.url.find("MessagePush") == -1:
if not check_sign(args):
logging.warning("身份认证失败")
message = "身份认证失败"
error = "身份认证失败"
code = -2
if "ts" not in args.keys() or int(args["ts"]) + 3e5 < int(time.time() * 1000):
logging.warning("拒绝本次请求")
message = "拒绝本次请求"
error = "拒绝本次请求"
code = -2
# if name and time.localtime(time.time())[3] < 7:
# logging.warning("非服务时间", )
# message = "非服务时间"
# error = "非服务时间"
# code = -1
elif request.path[1:] not in no_limit_url and not check_request_limit(request.args["key"]):
logging.warning("拒绝了 %s 的请求", request.args["key"])
message = "操作过频繁"
error = "操作过频繁"
code = -5
if name == "guest" and request.path[1:] in guest_data.keys():
data = guest_data[request.path[1:]]
if request.path[1:] in need_proxy_url and not global_values.get_value("proxy_status_ok"):
code = -7
message = "服务器网络故障"
logging.warning("服务器网络故障")
if code != 0 or len(data) > 1:
resp = Response(json.dumps({"message": message, "error": error, "code": code, "data": data}),
mimetype='application/json')
return resp
url = request.path + "?" + get_cache_key(dict(request.args))
url_md5 = hashlib.md5(url.encode()).hexdigest()
res_b = redis_cache.get(url_md5)
if res_b:
res = json.loads(res_b)
res["cached"] = 1
resp = Response(json.dumps(res), mimetype='application/json')
logging.info("命中缓存 %s", unquote(url))
return resp
def get_cache_key(args: dict):
if "sign" in args.keys():
del args["sign"]
if "ts" in args.keys():
del args["ts"]
args_list = []
for k in sorted(args):
args_list.append(k + "=" + args[k])
return "&".join(args_list)
def check_sign(args: dict):
if "sign" not in args.keys():
return False
sign = args["sign"]
del args["sign"]
args_list = []
for k in sorted(args):
args_list.append(k + "=" + quote(args[k], safe="~()*!.\'"))
arg = "&".join(args_list)
return sign == hashlib.md5((arg + appSecret).encode("utf-8")).hexdigest()
@app.after_request
def cache_request(response):
try:
res = json.loads(response.get_data())
if "cached" not in res.keys() and res["code"] == 0 and request.path[1:] not in dont_cache_url:
url = request.path + "?" + get_cache_key(dict(request.args))
redis_cache.set(hashlib.md5(url.encode()).hexdigest(), json.dumps(res), 5400)
logging.info("缓存 %s", unquote(url))
except:
pass
return response
def check_request_limit(user_key):
if redis_request_limit.llen(user_key) < 30:
redis_request_limit.lpush(user_key, time.time())
else:
first_time = redis_request_limit.lindex(user_key, -1)
if time.time() - float(first_time) < 300:
return False
else:
redis_request_limit.lpush(user_key, time.time())
redis_request_limit.ltrim(user_key, 0, 29)
redis_request_limit.expire(user_key, 3600)
return True
def initializer(context=None):
global_values.set_value("proxy_status_ok", True)
plugins = load_plugin.load_plugins(
path.join(path.dirname(__file__), 'plugins'),
'plugins'
)
plugins.union(load_plugin.load_plugins(
path.join(path.dirname(__file__), 'plugins_v2'),
'plugins_v2'
))
for i in plugins:
app.register_blueprint(i.api)
load_task.load_tasks(
path.join(path.dirname(__file__), 'tasks'),
'tasks')
scheduler.start()
if __name__ == '__main__':
initializer()
http_server = WSGIServer(('0.0.0.0', 100), app, log=root_logger, error_log=root_logger)
http_server.serve_forever()
def handler(environ, start_response):
return app(environ, start_response)
<file_sep># from redis_connect import redis_session as session
import json
import logging
import re
import traceback
import bs4
import html2text as ht
import requests
from utils.redis_connections import redis_news
from utils.scheduler import scheduler
type_dic = {"1013": "zbxw", "1014": "tzgg", "1354": "xshd"}
name_dic = {"1013": "news", "1014": "notice", "1354": "academic"}
def update_article(type_id):
import time
if time.localtime(time.time())[3] < 7:
return
type_ = type_dic[type_id]
type_name = name_dic[type_id]
logging.info("开始更新 " + type_name)
text_maker = ht.HTML2Text()
text_maker.ignore_links = True
session = requests.session()
article_url = "http://www.nuc.edu.cn/index/" + type_ + ".htm"
articles = []
while True:
article_html = session.get(article_url)
soup = bs4.BeautifulSoup(article_html.content, "html.parser")
article_list = soup.find_all(class_="list_con_rightlist")
article_list_a_tag = article_list[0].find_all("a")
flag = True
repeat_count = 0
for a in article_list_a_tag:
if "class" not in a.attrs.keys():
try:
res = re.search(type_id + r"/([0-9]{0,}).htm", a["href"])
if not res:
continue
news_id = res.group(1)
if redis_news.exists(type_name + news_id):
# if redis_server.llen(type_name+"_list")>0 and id == json.loads(redis_server.lindex(type_name+"_list",0))["id"]:
repeat_count += 1
if repeat_count > 3:
break
continue
news = session.get("http://www.nuc.edu.cn/info/" + type_id + "/" + news_id + ".htm")
news_soup = bs4.BeautifulSoup(news.content, "html.parser")
news_with_id = news_soup.find_all("div", {"id": re.compile(r"vsb_content")})
html = str(news_with_id[0]).replace("/__local", "http://www.nuc.edu.cn/__local")
text = text_maker.handle(html)
news_time = news_soup.find_all(style="line-height:400%;color:#444444;font-size:14px")[0]
res_time = re.search(r"时间:(.*)作者", str(news_time))
time = res_time.group(1).strip(" ")
articles.append(json.dumps({"id": news_id, "date": a.next_sibling.string, "title": a["title"]}))
redis_news.set(type_name + news_id,
json.dumps({"time": time, "title": a["title"], "content": text}))
logging.info("添加 " + a["title"])
except:
logging.error(traceback.format_exc())
logging.error("%s %s" % (a["title"], a["href"]))
elif a["class"][0] == "Next":
flag = False
if a.string == "下页":
article_url = "http://www.nuc.edu.cn/index/" + type_ + "/" + a["href"].replace(type_, "").replace(
"/", "")
if flag:
break
for x in reversed(articles):
redis_news.lpush(type_name + "_list", x)
logging.info("完成更新 " + type_name)
def update_news():
update_list = ["1013", "1014", "1354"]
for i in update_list:
update_article(i)
scheduler.add_job(update_news, 'interval', minutes=10)
<file_sep>import hashlib
import json
import os
from flask import Response
from flask import request
from qiniu import Auth, put_file
from plugins_v2._login_v2.login_v2 import login
from . import api
from .config import *
q = Auth(qiniu_access_key, qiniu_secret_key)
bucket_name = 'blog_cdn'
@api.route('/ExportGrade', methods=['GET'])
def handle_get_grade():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
file_type = request.args.get('type', "pdf")
res = get_grade(name, passwd, file_type)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def upload_to_qiniu(file_name):
token = q.upload_token(bucket_name, file_name, 3600)
put_file(token, file_name, file_name)
os.remove(file_name)
def get_grade(name, passwd, file_type):
message = "OK"
code = 0
data = []
if len(name) < 1 or len(passwd) < 1:
code = -2
message = "账号密码不能为空"
else:
session = login(name, passwd)
if isinstance(session, str):
code = -3
message = session
else:
if file_type == "pdf":
post_data1 = {
"gsdygx": "10353-zw-mrgs1"
}
pdf_message = session.post(pdf_url1, data=post_data1).content.decode()
if pdf_message.find("可打印") == -1:
code = -3
message = pdf_message
else:
pdf_url = session.post(pdf_url2, data=post_data1).content.decode().replace("\\", "").replace("\"",
"")
if pdf_url.find("成功") != -1:
pdf_content = session.get("http://172.16.31.109" + pdf_url.split("#")[0]).content
file_name = "files/%s-grade-%s.pdf" % \
(name, hashlib.md5((name + appSecret).encode("utf-8")).hexdigest()[:5])
with open(file_name, "wb") as pdf_file:
pdf_file.write(pdf_content)
upload_to_qiniu(file_name)
data = {
"url": "https://blog-cdn.dreace.top/" + file_name
}
else:
code = -3
message = pdf_url
else:
xls_content = session.post(excel_url, data=post_data).content
file_name = "files/%s-grade-%s.xls" % \
(name, hashlib.md5((name + appSecret).encode("utf-8")).hexdigest()[:5])
with open(file_name, "wb") as xls_file:
xls_file.write(xls_content)
upload_to_qiniu(file_name)
data = {
"url": "https://blog-cdn.dreace.top/" + file_name
}
return {"message": message, "code": code, "data": data}
<file_sep>import json
import pymysql
from DBUtils.PooledDB import PooledDB
NAME = ""
PASSWD = ""
proxies = {}
proxy_status_url = ""
get_cookies_url = ""
vpn_cookies = ""
redis_host = ""
redis_password = ""
redis_port = 6379
mysql_host = ""
mysql_user = ""
mysql_password = ""
qiniu_access_key = ''
qiniu_secret_key = ''
guest_data = {}
with open("data/guest_data.json", encoding="utf-8") as file:
guest_data = json.loads(file.read())
no_limit_url = {"GetNews", "v2/fitness/captcha"}
dont_cache_url = {"Token", "ToiCal", "GetNews", "v2/fitness/captcha"}
stopped_list = {"LoginPhyEws", "GetIdleClassroom", "PhysicalFitnessTestLogin"}
need_proxy_url = {"SearchLibrary", "v2/GetCourseTable", "v2/ExportGrade", "v2/GetGrade", "v2/Login",
"PhysicalFitnessTestGetScoreList", "PhysicalFitnessTestGetScore", "PhysicalFitnessTestLogin",
"GetBookAvailableDetail", "GetClassCourseTable", "SearchLibraryByISBN", "SearchLibrary", "GetCourse",
"v2/fitness/list", "v2/fitness/login", "v2/fitness/detail", "v2/fitness/captcha"}
appSecret = ''
mysql_pool = PooledDB(
creator=pymysql, # 使用链接数据库的模块
maxconnections=10, # 连接池允许的最大连接数,0和None表示不限制连接数
mincached=5, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
maxcached=5, # 链接池中最多闲置的链接,0和None不限制
maxshared=3,
# 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制
setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
ping=0,
# ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is
# created, 4 = when a query is executed, 7 = always
host=mysql_host,
port=3306,
user=mysql_user,
password=<PASSWORD>,
database='nuc_info',
charset='utf8'
)
<file_sep>from global_config import *
captcha_code_url = "http://tygl.nuc.edu.cn/code/captcha-image"
login_url = "http://tygl.nuc.edu.cn/admin/login"
info_url = "http://tygl.nuc.edu.cn/admin/measure/stuScorelist"
grade_list_url= "http://tygl.nuc.edu.cn/app/measure/getStuTotalScore"
grade_detail_url = "http://tygl.nuc.edu.cn/app/measure/getStuScoreDetail"
<file_sep>from flask import Blueprint
api = Blueprint('get_course_table_api_v2', __name__, url_prefix="/v2")
from .get_course_table_v2 import *
<file_sep>import re
import requests
from .config import proxies, PhyEws_post_url, PhyEws_url
def login_PhyEws(name, passwd):
session = requests.session()
session.proxies = proxies
html = session.get(PhyEws_url).content
reg = re.search("name=\"__VIEWSTATE\" value=\"(.{0,})\"", html)
__VIEWSTATE = reg.group(1)
data = {
"__VIEWSTATE": __VIEWSTATE,
"login1:StuLoginID": name,
"login1:StuPassword": <PASSWORD>,
"login1:UserRole": "Student",
"login1:btnLogin.x": "12",
"login1:btnLogin.y": "6",
}
r = session.post(PhyEws_post_url, data=data)
if r.content.decode("gbk").find(u"用户或密码错误") != -1:
return 2
return session
<file_sep>import re
import traceback
from urllib.parse import quote
import bs4
import requests
from flask import Response
from flask import request
from gevent.pool import Pool
from . import api
from .config import *
requests.packages.urllib3.disable_warnings()
session = requests.session()
session.proxies = proxies
session.verify = False
@api.route('/SearchLibrary', methods=['GET'])
def search_library():
session.headers = {"Cookie": global_values.get_value("vpn_cookies")}
book_type = request.args.get("type", "正题名")
book_name = request.args.get('keyword', "")
page = request.args.get('page', "1")
res = search(book_type, book_name, page)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/SearchLibraryByISBN', methods=['GET'])
def search_library_isbn():
session.headers = {"Cookie": global_values.get_value("vpn_cookies")}
isbn = request.args.get('keyword', "")
res = search_by_isbn(isbn)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/GetBookAvailableDetail', methods=['GET'])
def get_book_available_detail():
session.headers = {"Cookie": global_values.get_value("vpn_cookies")}
book_id = request.args.get('BookID', "")
res = get_available_book_detail(book_id)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_available_book_detail(book_id) -> dict:
message = "OK"
error = ""
code = 0
data = []
try:
url = "http://222-31-39-3-8080-p.vpn.nuc1941.top:8118//pft/showmarc/showbookitems.asp?nTmpKzh=%s" % book_id
content = session.get(url).content.decode("utf-8")
soups = bs4.BeautifulSoup(content, "html.parser")
trs = soups.find_all("tr")
if len(trs) > 1:
for td in trs[1:]:
tds = td.find_all("td")
data.append({"number": "".join(tds[1].text.split()),
"barcode": "".join(tds[2].text.split()),
"location": "".join(tds[3].text.split()),
"status": "".join(tds[4].text.split())})
except:
message = "发生异常"
error = "服务器内部错误"
code = -1
return {"message": message, "error": error, "code": code, "data": data}
def search_by_isbn(isbn) -> dict:
message = "OK"
error = ""
code = 0
data = {}
if len(isbn) != 13 and len(isbn) != 10:
message = "参数错误"
error = "非法的 ISBN 编号"
code = -1
else:
if len(isbn) == 10:
isbn = isbn[:1] + "-" + isbn[1:5] + "-" + isbn[5:9] + "-" + isbn[9:]
else:
isbn = isbn[:3] + "-" + isbn[3:4] + "-" + isbn[4:7] + "-" + isbn[7:12] + "-" + isbn[12:]
try:
url = "http://222-31-39-3-8080-p.vpn.nuc1941.top:8118//pft/wxjs/bk_s_Q_fillpage.asp?q=标准编号=[[%s*]]" \
"&nmaxcount=&nSetPageSize=10&orderby=&Research=1&page=1&opt=1" % (quote(isbn))
content = session.get(url).content.decode('utf-8')
re_book_ids = re.findall(r"ShowItem\('([0-9]*)'\)", content)
records_group = re.search(r"共([0-9]*)条记录", content)
if records_group is None:
message = "无结果"
code = -1
error = "没有找到任何匹配结果"
else:
records = records_group.group(1)
pool = Pool(10)
book_list = pool.map(get_book_detail, re_book_ids)
data = {"total_records": records, "page": 1, "page_records": len(book_list), "list": book_list}
except:
traceback.print_exc()
message = "发生异常"
code = -1
error = "服务器内部错误"
return {"message": message, "error": error, "code": code, "data": data}
def search(book_type, keyword, page=1) -> dict:
message = "OK"
error = ""
code = 0
data = {}
try:
url = "http://222-31-39-3-8080-p.vpn.nuc1941.top:8118//pft/wxjs/bk_s_Q_fillpage.asp?q=%s=[[%s*]]" \
"&nmaxcount=&nSetPageSize=10&orderby=&Research=1&page=%s&opt=1" % (quote(book_type), quote(keyword), page)
content = session.get(url).content.decode('utf-8')
re_book_ids = re.findall(r"ShowItem\('([0-9]*)'\)", content)
records_group = re.search(r"共([0-9]*)条记录", content)
if records_group is None:
message = "无结果"
code = -1
error = "没有找到任何匹配结果"
else:
records = records_group.group(1)
pool = Pool(10)
book_list = pool.map(get_book_detail, re_book_ids)
data = {"total_records": records, "page": 1, "page_records": len(book_list), "list": book_list}
except:
message = "发生异常"
code = -1
error = "服务器内部错误"
return {"message": message, "error": error, "code": code, "data": data}
def get_book_detail(book_id) -> dict:
url = "http://222-31-39-3-8080-p.vpn.nuc1941.top:8118//pft/showmarc/table.asp?nTmpKzh=%s" % book_id
content = session.get(url).content
soups = bs4.BeautifulSoup(content, "html.parser")
details = soups.find(id="tabs-2").find_all("tr")
detail_dict = {}
detail_dict["id"] = book_id
detail_dict["available_books"] = get_book_available(book_id)
for i in details:
tds = i.find_all("td")
if tds[0].text.strip() == "010":
info = tds[2].text.strip().split("@")
for j in info:
if len(j) < 1:
continue
if j[0] == "a":
detail_dict["ISBN"] = j[1:]
detail_dict["cover_url"] = douban_book_cover(j[1:])
elif tds[0].text.strip() == "200":
info = tds[2].text.strip().split("@")
for j in info:
if len(j) < 1:
continue
if j[0] == "a":
detail_dict["name"] = j[1:]
elif j[0] == "f":
detail_dict["author"] = j[1:]
elif j[0] == "g":
detail_dict["translator"] = j[1:]
elif tds[0].text.strip() == "210":
info = tds[2].text.strip().split("@")
for j in info:
if len(j) < 1:
continue
if j[0] == "c":
detail_dict["press"] = j[1:]
elif j[0] == "d":
detail_dict["year"] = j[1:]
elif j[0] == "g":
detail_dict["translator"] = j[1:]
elif tds[0].text.strip() == "330":
info = tds[2].text.strip().split("@")
for j in info:
if len(j) < 1:
continue
if j[0] == "a":
detail_dict["introduction"] = j[1:]
if "cover_url" not in detail_dict.keys():
detail_dict[
"cover_url"] = "https://img1.doubanio.com/f/shire/5522dd1f5b742d1e1394a17f44d590646b63871d/pics/book-default-lpic.gif"
return detail_dict
def get_book_available(boo_id) -> str:
url = "http://222-31-39-3-8080-p.vpn.nuc1941.top:8118//pft/wxjs/BK_getKJFBS.asp"
post_data["nkzh"] = boo_id
content = session.post(url, data=post_data).content.decode()
return content
douban_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
"DNT": "1",
"Accept": "*/*",
"Sec-Fetch-Site": "cross-site",
"Sec-Fetch-Mode": "cors",
"Accept-Encoding": "gzip",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
def douban_book_cover(isbn):
try:
url = "https://api.douban.com/v2/book/isbn/%s?apikey=0df993c66c0c636e29ecbb5344252a4a" % isbn
res = requests.get(url, headers=douban_headers, verify=False)
book_json = json.loads(res.content.decode())
if "images" in book_json.keys():
return book_json["images"]["small"]
else:
return "https://img1.doubanio.com/f/shire/5522dd1f5b742d1e1394a17f44d590646b63871d/pics/book-default-lpic.gif"
except:
traceback.print_exc()
return "https://img1.doubanio.com/f/shire/5522dd1f5b742d1e1394a17f44d590646b63871d/pics/book-default-lpic.gif"
<file_sep>import json
import pymysql
from flask import Response
from flask import request
from utils.sql_helper import SQLHelper
from . import api
@api.route('/GetCourse', methods=['GET'])
def handle_get_course():
keywords = request.args.get('keywords', "")
res = get_course(keywords)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_course(keywords):
message = "OK"
error = ""
code = 0
data = []
keywords = pymysql.escape_string(keywords)
keywords_map = "".join(map(lambda k: "(?=.*%s)" % k, keywords.split(" ")))
sql = "SELECT * FROM `课程-2020-1` WHERE CONCAT_WS('', `学院`, `课程名`, `教师`) REGEXP '%s^.*$'" % keywords_map
for index, row in enumerate(SQLHelper.fetch_all(sql)):
data.append({
"ID": index + 1,
"Department": row["学院"],
"Course_name": row["课程名"],
"Teacher": row["教师"],
"Time": row["周次"],
"Week": row["星期"],
"Class_time": "%s~%s" % (row["开始节次"], row["开始节次"] + row["时长节次"] - 1),
"Teaching_building": row["教学楼"],
"Classroom": row["教室"]
})
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>from flask import Blueprint
api = Blueprint('get_idle_classroom_api', __name__)
from .get_idle_classroom import *<file_sep>from flask import request
from flask import Response
from plugins._login_PhyEws.login_PhyEws import login_PhyEws
import json
from . import api
@api.route('/LoginPhyEws', methods=['GET'])
def handle_get_course():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
res = login_PhyEws_(name, passwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def login_PhyEws_(name, passwd):
message = "登录成功"
error = ""
code = 0
data = "0"
if len(name) < 1 or len(passwd) < 1:
code = -2
message = "登陆失败"
error = "账号密码不能为空"
else:
session = login_PhyEws(name, passwd)
if type(1) == type(session):
code = -1
message = "登陆失败"
if session == 2:
error = "账号或密码错误"
else:
error = "服务器异常"
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>from flask import Blueprint
api = Blueprint('login_PhyEws_api', __name__)
from .login_PhyEws import *<file_sep>from flask import Blueprint
api = Blueprint('get_news_api', __name__)
from .get_news import *<file_sep>本仓库为 [中北信息](https://github.com/Dreace/NUC-Information) 小程序的后端,使用 Python 编写。
# 安装依赖
```
pip install -r requirements.txt
```
# 启动服务端
```
python index.py
```
# 状态码(全局使用)
| 值 | 状态 |
|----|-----|
|0|正常|
|-1|服务器错误|
|-2|认证失败|
|-3|登录失败|
|-4|暂停服务|
|-5|访问过快|
|-6|查询失败|
|-7|查询失败|
# 状态码(组件特定)
| 值 | 状态 | 组件 |
|----|-----|-----|
|1|登陆失败(可能是验证码错误)|体测
<file_sep>from flask import Blueprint
from flask import request
from flask import Response
from utils.redis_connections import redis_token
import hashlib
import base64
import random
import string
import json
api = Blueprint('get_token_api', __name__)
@api.route('/Token', methods=['GET'])
def get_token():
key = request.args.get('key', "")
sign = request.args.get('sign', "")
res = generate_token(key, sign)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def generate_token(key, sign):
message = "OK"
error = ""
code = 0
data = ""
if hashlib.md5(base64.b64encode(key.encode("utf-8"))).hexdigest() != sign:
message = "鉴权失败"
error = "非法 Key"
code = -1
else:
key += ''.join(random.choices(string.ascii_letters + string.digits, k=12))
token = hashlib.md5(base64.b64encode(key.encode("utf-8"))).hexdigest()
redis_token.set(token, token, ex=3600)
data = {
"token": token
}
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>login_url = "http://tygl.nuc.edu.cn/app/appstu/login"
mea_score_id_url = "http://tygl.nuc.edu.cn/app/measure/getStuTotalScore"
score_detail_url = "http://tygl.nuc.edu.cn/app/measure/getStuScoreDetail"
from global_config import proxies
app = "appId=76a9c9f0e5ae4d2d84bf6eda1613ddbf&appSecret=<KEY>&"
headers = {
"User-Agent": "StudentsMarch/2.6.2 (iPhone; iOS 13.2; Scale/3.00)",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}
<file_sep>from flask import Blueprint
api = Blueprint('export_grade_api_v2', __name__, url_prefix="/v2")
from .export_grade_v2 import *
<file_sep>import json
import pymysql
from flask import Response
from flask import request
from utils.sql_helper import SQLHelper
from . import api
@api.route('/GetNoticeList', methods=['GET'])
def handle_get_notice_list():
res = get_notice()
resp = Response(json.dumps(res), mimetype="application/json")
return resp
@api.route('/GetOneNoticeContent', methods=['GET'])
def handle_get_one_notice_content():
notice_id = int(request.args.get("id"))
res = get_one_notice_content(notice_id)
resp = Response(json.dumps(res), mimetype="application/json")
return resp
@api.route('/GetNewNotice', methods=['GET'])
def handle_get_new_notice():
res = get_new_notice()
resp = Response(json.dumps(res), mimetype="application/json")
return resp
def get_new_notice():
sql = "SELECT max(id) id FROM `notice`"
notice_id = SQLHelper.fetch_one(sql)
res = get_one_notice_content(notice_id["id"])
return res
def get_one_notice_content(notice_id: int):
message = ""
error = ""
code = 0
data = ""
notice_id = pymysql.escape_string(str(notice_id))
sql = "SELECT `内容`,`时间`,`标题`,`id`,`重要` FROM notice WHERE id = %s" % notice_id
result = SQLHelper.fetch_one(sql)
if result is None:
message = "没有内容"
error = "没有数据"
code = -6
else:
data = {
"content": result["内容"],
"time": str(result["时间"]),
"title": result["标题"],
"id": result["id"],
"importance": result["重要"]
}
res = {
"message": message,
"error": error,
"code": code,
"data": data
}
return res
def get_notice():
message = "没有公告"
error = "没有数据"
code = -6
data = ""
sql = "SELECT * FROM `notice` "
# 所有公告
results = SQLHelper.fetch_all(sql)
if len(results) >= 1:
notices = {"top": [], "normal": []}
message = ""
error = ""
code = 0
for res in results:
is_top = res["是否置顶"]
notice = {
"id": res["id"],
"title": res["标题"],
"time": str(res["时间"])
}
if is_top:
notices["top"].append(notice)
else:
notices["normal"].append(notice)
notices["top"] = list(reversed(notices["top"]))
notices["normal"] = list(reversed(notices["normal"]))
data = notices
res = {
"message": message,
"error": error,
"code": code,
"data": data
}
return res
<file_sep>import json
from flask import Response
from flask import request
from utils.sql_helper import SQLHelper
from . import api
@api.route('/GetExam', methods=['GET'])
def handle_get_exam():
keywords = request.args.get('keywords', "")
res = get_exam(keywords)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_exam(keywords):
message = "OK"
error = ""
code = 0
data = []
names = ["course_name", "class"]
sql = "SELECT * FROM `exam` WHERE "
for j in names:
args = (j, keywords.split()[0])
sql += "`%s` LIKE '%%%s%%' OR " % (args)
if sql.find("OR") != 0:
results = SQLHelper.fetch_all(sql[:-4])
for row in results:
r = {
"course_name": row[2],
"time": row[3],
"date": row[4],
"class": row[5],
"classroom": row[6]
}
# TODO 若重新启用,把上面改为列名
data.append(r)
for j in keywords.split()[1:]:
a = []
for i in data:
if i["course_name"].find(j) != -1 or i["class"].find(j) != -1:
a.append(i)
data = a
return {"message": message, "error": error, "code": code, "data": data}
<file_sep># coding=utf-8
import hashlib
import json
import logging
import ssl
import time
import requests
from flask import Response
from flask import request
from . import api
from .config import app, login_url, headers, mea_score_id_url, score_detail_url, proxies
ssl._create_default_https_context = ssl._create_unverified_context
@api.route('/PhysicalFitnessTestLogin', methods=['GET'])
def handle_physical_fitness_test_login():
name = request.args.get('name')
pwd = request.args.get('passwd')
res = login(name, pwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/PhysicalFitnessTestGetScoreList', methods=['GET'])
def handle_physical_fitness_test_get_score_list():
id_ = request.args.get('id')
res = get_score_list(id_)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
@api.route('/PhysicalFitnessTestGetScore', methods=['GET'])
def handle_physical_fitness_test_get_score():
id_ = request.args.get('id')
res = get_score(id_)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def login(name, pwd):
message = "登录成功"
error = ""
code = 0
data = "0"
time_now = int(round(time.time() * 1000))
url_data = "%spwd=%s×tamp=%s&uname=%s" % (app, pwd, time_now, name)
sign = hashlib.md5(url_data.encode()).hexdigest()
url_data = "pwd=%s&sign=%s×tamp=%s&uname=%s" % (pwd, sign, time_now, name)
res = requests.post(login_url, data=url_data, headers=headers, proxies=proxies).content
res_json = json.loads(res)
if res_json["returnCode"] == '200':
data = res_json["data"]
else:
message = res_json["returnMsg"]
code = -1
return {"message": message, "error": error, "code": code, "data": data}
def get_score_list(id_):
message = "OK"
error = ""
code = 0
data = "0"
time_now = int(round(time.time() * 1000))
url_data = "%stimestamp=%s&userId=%s" % (app, time_now, id_)
sign = hashlib.md5(url_data.encode()).hexdigest()
url_data = "sign=%s×tamp=%s&userId=%s" % (sign, time_now, id_)
res = requests.post(mea_score_id_url, data=url_data, headers=headers, proxies=proxies).content
res_json = json.loads(res)
if res_json["returnCode"] == '200':
data = res_json["data"]
else:
message = res_json["returnMsg"]
code = -1
return {"message": message, "error": error, "code": code, "data": data}
def get_score(id_):
message = "OK"
error = ""
code = 0
data = "0"
time_now = int(round(time.time() * 1000))
url_data = "%s&meaScoreId=%s×tamp=%s" % (app, id_, time_now)
sign = hashlib.md5(url_data.encode()).hexdigest()
url_data = "sign=%s&meaScoreId=%s×tamp=%s" % (sign, id_, time_now,)
res = requests.post(score_detail_url, data=url_data, headers=headers, proxies=proxies).content
res_json = json.loads(res)
if res_json["returnCode"] == '200':
data = res_json["data"]
else:
message = res_json["returnMsg"]
code = -1
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>from global_config import *
PhyEws_grade_url = "http://172.16.58.3/PhyEws/student/select.aspx"
<file_sep>import json
from flask import Response
from flask import request
from utils.redis_connections import redis_news
from . import api
@api.route('/GetNews', methods=['GET'])
def handle_get_news():
op = request.args.get('op', "")
page = request.args.get('page', "1")
id = request.args.get('id', "")
type_id = request.args.get('type', "")
res = get_news(op, int(page), id, type_id)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
# type_dic = {"1013": "zbxw", "1014": "tzgg", "1354": "xshd"}
name_dic = {"1013": "news", "1014": "notice", "1354": "academic"}
def get_news(op, page, id_, type_id):
message = "OK"
error = ""
code = 0
data = []
type_name = name_dic[type_id]
if op == "1":
cnt = redis_news.llen(type_name + "_list")
data = {"count": cnt}
elif op == "2":
page -= 1
news_list = redis_news.lrange(type_name + "_list", page * 15, page * 15 + 14)
new_list = []
for i in news_list:
new_list.append(json.loads(i))
data = new_list
elif op == "3":
data = json.loads(redis_news.get(type_name + id_))
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>import hashlib
import json
import os
import random
import re
from datetime import date, datetime
from uuid import uuid1
from dateutil.relativedelta import relativedelta
from flask import Response
from flask import request
from icalendar import Calendar, Event
from pytz import timezone
from qiniu import Auth, put_file
from global_config import qiniu_access_key, qiniu_secret_key
cst_tz = timezone('Asia/Shanghai')
utc_tz = timezone('UTC')
from . import api
q = Auth(qiniu_access_key, qiniu_secret_key)
bucket_name = 'blog_cdn'
@api.route('/ToiCal', methods=['POST'])
def handle_to_ical():
arguments = request.get_json()
data = arguments["data"]
first_monday = arguments["firtMonday"]
res = to_ical(data, first_monday)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def display(cal):
return cal.to_ical().decode('utf-8').replace('\r\n', '\n').strip()
def write_ics_file(name, ics_text):
path_name = "./files/" + name
with open(path_name, "w", encoding='utf-8') as file:
file.write(display(ics_text))
key = 'files/%s' % name
token = q.upload_token(bucket_name, key, 3600)
ret, info = put_file(token, key, path_name)
os.remove(path_name)
def generate_random_str(random_length=16):
random_str = ''
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
length = len(base_str) - 1
for i in range(random_length):
random_str += base_str[random.randint(0, length)]
return random_str
def to_ical(table, first_monday):
message = "OK"
error = ""
code = 0
data = {}
rule = re.compile(r"[^a-zA-Z0-9\-,]")
cal = Calendar()
cal['version'] = '2.0'
cal['prodid'] = '-//NUC//Syllabus//CN' # *mandatory elements* where the prodid can be changed, see RFC 5445
mondaySplit = first_monday.split('-')
start_monday = date(int(mondaySplit[0]), int(mondaySplit[1]), int(mondaySplit[2])) # 开学第一周星期一的时间
dict_day = {1: relativedelta(hours=8, minutes=0), 3: relativedelta(hours=10, minutes=10),
5: relativedelta(hours=14, minutes=30), 7: relativedelta(hours=16, minutes=40),
9: relativedelta(hours=19, minutes=30)}
dict_day2 = {1: relativedelta(hours=8, minutes=0), 3: relativedelta(hours=10, minutes=10),
5: relativedelta(hours=14, minutes=0), 7: relativedelta(hours=16, minutes=10),
9: relativedelta(hours=19, minutes=0)}
for i in table:
if "Course_Week" not in i:
continue
for j in rule.sub('', i["Course_Week"]).split(','):
if j.find('-') != -1:
d = j.split('-')
for dday in range(int(d[0]), int(d[1]) + 1):
event = Event()
dtstart_date = start_monday + relativedelta(
weeks=(dday - 1)) + relativedelta(days=int(int(i["Course_Time"])) - 1)
dtstart_datetime = datetime.combine(dtstart_date, datetime.min.time())
if dtstart_date.month >= 5 and dtstart_date.month < 10:
dtstart = dtstart_datetime + dict_day[int(i["Course_Start"])]
else:
dtstart = dtstart_datetime + dict_day2[int(i["Course_Start"])]
dtend = dtstart + relativedelta(hours=1, minutes=40)
event.add('X-WR-TIMEZONE', 'Asia/Shanghai')
event.add('uid', str(uuid1()) + '@Dreace')
event.add('summary', i["Course_Name"])
event.add('dtstamp', datetime.now())
event.add('dtstart', dtstart.replace(tzinfo=cst_tz).astimezone(cst_tz))
event.add('dtend', dtend.replace(tzinfo=cst_tz).astimezone(cst_tz))
event.add('rrule',
{'freq': 'weekly', 'interval': 1,
'count': 1})
event.add('location', i["Course_Building"] + i["Course_Classroom"])
cal.add_component(event)
else:
if j == '':
continue
event = Event()
dtstart_date = start_monday + relativedelta(
weeks=(int(j) - 1)) + relativedelta(days=int(int(i["Course_Time"])) - 1)
dtstart_datetime = datetime.combine(dtstart_date, datetime.min.time())
if dtstart_date.month >= 5 and dtstart_date.month < 10:
dtstart = dtstart_datetime + dict_day[int(i["Course_Start"])]
else:
dtstart = dtstart_datetime + dict_day2[int(i["Course_Start"])]
dtend = dtstart + relativedelta(hours=1, minutes=40)
event.add('X-WR-TIMEZONE', 'Asia/Shanghai')
event.add('uid', str(uuid1()) + '@Dreace')
event.add('summary', i["Course_Name"])
event.add('dtstamp', datetime.now())
event.add('dtstart', dtstart.replace(tzinfo=cst_tz).astimezone(cst_tz))
event.add('dtend', dtend.replace(tzinfo=cst_tz).astimezone(cst_tz))
event.add('rrule',
{'freq': 'weekly', 'interval': 1,
'count': 1})
event.add('location', i["Course_Building"] + i["Course_Classroom"])
cal.add_component(event)
filename = hashlib.md5(json.dumps(table).encode('utf8')).hexdigest().upper() + ".ics"
write_ics_file(filename, cal)
data["url"] = "https://blog-cdn.dreace.top/files/" + filename
return {"message": message, "error": error, "code": code, "data": data}
<file_sep>from global_config import *
PhyEws_url = "http://172.16.58.3/PhyEws/"
PhyEws_post_url = "http://172.16.58.3/PhyEws/default.aspx"
<file_sep>from flask import Response
from flask import request
from plugins_v2._login_v2.login_v2 import login
from . import api
from .config import *
@api.route('/GetGrade', methods=['GET'])
def handle_get_grade():
name = request.args.get('name', "")
passwd = request.args.get('passwd', "")
res = get_grade(name, passwd)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_grade(name, passwd):
message = "OK"
code = 0
data = []
if len(name) < 1 or len(passwd) < 1:
code = -2
message = "账号密码不能为空"
else:
session = login(name, passwd)
if isinstance(session, str):
code = -3
message = session
else:
post_data = {
"queryModel.showCount": 1000,
}
grade = session.post(grade_url, post_data).json()
grades = {}
for item in grade["items"]:
dict_key = item["xnmmc"] + "-" + item["xqmmc"]
if dict_key not in grades:
grades[dict_key] = []
grades[dict_key].append({
"Course_Name": item["kcmc"] if "kcmc" in item else "",
"Course_Credit": float(item["xf"]) if "xf" in item else "",
"Course_Grade": item["bfzcj"],
"Course_Grade_Point": float(item["jd"]) if "jd" in item else ""
})
data = list(grades.values())
g_a, g_b = 0, 0
for item_i in data:
a, b = 0, 0
for item_j in item_i:
if item_j["Course_Credit"] and item_j["Course_Grade_Point"]:
t = item_j["Course_Credit"] * item_j["Course_Grade_Point"]
a += t
g_a += t
b += item_j["Course_Credit"]
g_b += item_j["Course_Credit"]
if b:
item_i.append({
"Course_Name": "学期平均绩点",
"Course_Grade_Point": round(a / b, 2)
})
if g_b:
data[-1].append({
"Course_Name": "总平均绩点",
"Course_Grade_Point": round(g_a / g_b, 2)
})
return {"message": message, "code": code, "data": data}
<file_sep>from global_config import qiniu_access_key,qiniu_secret_key,appSecret
pdf_url1 = "http://192.168.127.12/jwglxt/bysxxcx/xscjzbdy_cxXsCount.html?gnmkdm=N558020"
pdf_url2 = "http://172.16.17.329/jwglxt/bysxxcx/xscjzbdy_dyList.html?gnmkdm=N558020"
excel_url = "http://192.168.127.12/jwglxt/cjcx/cjcx_dcListByXs.html"
post_data = [
("gnmkdmKey", "N305005"),
("dcclbh", "JW_N305005_XSCXCJ"),
("queryModel.sortName", ""),
("queryModel.sortOrder", "asc"),
("exportModel.selectCol", "xnmmc@学年"),
("exportModel.selectCol", "xqmmc@学期"),
("exportModel.selectCol", "kch@课程代码"),
("exportModel.selectCol", "kcmc@课程名称"),
("exportModel.selectCol", "kcxzmc@课程性质"),
("exportModel.selectCol", "xf@学分"),
("exportModel.selectCol", "cj@成绩"),
("exportModel.selectCol", "bfzcj@百分制成绩"),
("exportModel.selectCol", "cjbz@成绩备注"),
("exportModel.selectCol", "jd@绩点"),
("exportModel.selectCol", "ksxz@成绩性质"),
("exportModel.selectCol", "cjsfzf@是否成绩作废"),
("exportModel.selectCol", "sfxwkc@是否学位课程"),
("exportModel.selectCol", "kkbmmc@开课学院"),
("exportModel.selectCol", "kcbj@课程标记"),
("exportModel.selectCol", "kclbmc@课程类别"),
("exportModel.selectCol", "kcgsmc@课程归属"),
("exportModel.selectCol", "jxbmc@教学班"),
("exportModel.selectCol", "jsxm@任课教师"),
("exportModel.selectCol", "khfsmc@考核方式"),
("exportModel.selectCol", "xh@学号"),
("exportModel.selectCol", "xm@姓名"),
("exportModel.selectCol", "xb@性别"),
("exportModel.selectCol", "xslb@学生类别"),
("exportModel.selectCol", "jgmc@学院"),
("exportModel.selectCol", "zymc@专业"),
("exportModel.selectCol", "njmc@年级"),
("exportModel.selectCol", "bj@班级"),
("exportModel.exportWjgs", "xls"),
("fileName", "grade-export")
]
<file_sep>from global_config import *
course_table_url = "http://172.16.31.10/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151"
<file_sep>import json
import logging
from flask import Response
from flask import request
from plugins_v2._login_v2.login_v2 import login
from . import api
from .config import class_course_table_url, pre_class_course_table_url, NAME, PASSWD
@api.route('/GetClassCourseTable', methods=['GET'])
def handle_get_course_table():
class_name = request.args.get('class', "")
res = get_class_course_table(class_name)
resp = Response(json.dumps(res), mimetype='application/json')
return resp
def get_class_course_table(class_name):
message = "OK"
code = 0
data = []
if len(class_name) < 1:
code = -6
message = "关键词不能为空"
else:
session = login(NAME, PASSWD)
if isinstance(session, str):
code = -2
message = "查询失败"
logging.warning("全局账号登录失败:%s" % message)
else:
post_data = {
"xnm": "2019",
"xqm": "12",
"xqh_id": "01",
"njdm_id": "",
"jg_id": "",
"zyh_id": "",
"zyfx_id": "",
"bh_id": class_name,
"_search": "false",
"queryModel.showCount": "1",
}
pre_data = session.post("http://222.31.49.139/jwglxt/kbdy/bjkbdy_cxBjkbdyTjkbList.html?gnmkdm=N214505",
data=post_data).json()
if not pre_data["items"]:
code = -6
message = "无效的班级号"
else:
post_data = {
"xnm": "2019",
"xqm": "12",
"xqh_id": "01",
"njdm_id": "",
"jg_id": "",
"zyh_id": "",
"zyfx_id": "",
"bh_id": class_name,
"_search": "false",
"queryModel.showCount": "1",
}
pre_data = session.post(pre_class_course_table_url, data=post_data).json()
if not pre_data["items"]:
code = -6
message = "无效的班级号"
else:
post_data = {
"xnm": "2019",
"xqm": "12",
"xnmc": "2019-2020",
"xqmmc": "2",
"xqh_id": "01",
"njdm_id": pre_data["items"][0]["njdm_id"],
"zyh_id": pre_data["items"][0]["zyh_id"],
"bh_id": class_name,
"tjkbzdm": "1",
"tjkbzxsdm": "0",
# "zxszjjs": True
}
course_table = session.post(class_course_table_url, data=post_data).json()
tables = []
cnt = 0
name_dict = {}
for index, table in enumerate(course_table["kbList"]):
spited = table["jcor"].split("-")
if table["kcmc"] not in name_dict:
name_dict[table["kcmc"]] = cnt
cnt += 1
tables.append({
# "Course_Number": table["kch_id"],
"Course_Name": table["kcmc"],
# "Course_Credit": table["xf"],
# "Course_Test_Type": table["khfsmc"],
"Course_Teacher": table.get("xm"),
"Course_Week": table["zcd"],
"Course_Color": name_dict[table["kcmc"]],
"Course_Time": table["xqj"],
"Course_Start": spited[0],
"Course_Length": int(spited[1]) - int(spited[0]) + 1,
"Course_Building": table.get("xqmc"),
"Course_Classroom": table.get("cdmc")
})
# for d in course_table["sjkList"]:
# tables.append({
# "Course_Name": d["sjkcgs"]
# })
# TODO 兼容现有客户端
data = tables
return {"message": message, "code": code, "data": data}
<file_sep># coding=utf-8
import datetime
import json
from datetime import datetime
import pytz
import requests
from plugins.balance import config
import ssl
import bs4
from flask import request
from flask import Response
from .config import proxies
from flask import current_app
from . import api
ssl._create_default_https_context = ssl._create_unverified_context
post_data = config.post_data
@api.route('/CardBalance', methods=['GET'])
def handle_balance():
student_code = request.args.get('name')
balance = get_balance(student_code)
resp = Response(json.dumps(balance), mimetype='application/json')
return resp
def get_balance(student_code):
message = "OK"
error = ""
code = 0
balance_data = "0"
name_data = "未知"
cst_tz = pytz.timezone('Asia/Shanghai')
time_now = datetime.now(cst_tz)
local_time_hour = time_now.timetuple()[3]
if local_time_hour >= 22 or local_time_hour <= 1:
message = "非服务时间"
error = "非服务时间"
code = -1
else:
session = requests.session()
session.proxies = proxies
session.get(config.url1)
post_data["paymentContent"] = "busiCode=%s" % student_code
content = session.post(config.url2, data=config.post_data).content
soups = bs4.BeautifulSoup(content, "html.parser")
balance = soups.find_all(id="item37")
name = soups.find_all(id="item31")
if len(balance) < 1:
message = "没有数据"
error = "没有数据"
code = -1
else:
balance_data = balance[0].text
if len(name) > 0:
name_data = name[0].text
res = {
"message": message,
"error": error,
"code": code,
"data": {
"balance": balance_data,
"name": name_data,
"time": time_now.strftime("%Y-%m-%d %H:%M")
}
}
return res
<file_sep>from flask import Blueprint
api = Blueprint('fitness_api_v2', __name__, url_prefix="/v2/fitness")
from .physical_fitness_test_v2 import *
<file_sep>from global_config import *
from utils.gol import global_values
post_data = {
"nkzh": ""
}
<file_sep>from flask import Blueprint
api = Blueprint('login_api_v2', __name__, url_prefix="/v2")
from .login_v2 import *
| 1541e6da5d6ba7ee1ad4f8e17a3efd2ded8819f3 | [
"Markdown",
"Python"
] | 59 | Python | jasnzhuang/NUC-Information-Backend | 933ad5d01032383060bc9fbae78639b179b3ba9e | d3be0c2006e317be9184e05a96c16f6420d5940f |
refs/heads/master | <file_sep>let db = require('../config/mysql.config').db;
let request = require('request');
function getAll(callback) {
let query = "SELECT m.id, m.name, c.weightKgs as Kilograms, c.weightLbs as Pounds " +
"FROM models m JOIN capacities c ON m.capacity=c.id";
db.query(query, (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
function getPrograms(name, callback) {
let query = "SELECT m.id, m.name, c.weightKgs as Kilograms, c.weightLbs as Pounds, p.id as idProgram, p.name as programName, p.temperature, p.time, d.rpm as centrifuge, p.prewash, p.wash, p.rinse " +
"FROM models m JOIN capacities c ON m.capacity=c.id JOIN models_programs mp ON m.id=mp.idModel JOIN programs p ON mp.idProgram=p.id JOIN centrifuges d ON p.defaultCentrifuge=d.id " +
"WHERE m.name=? ORDER BY idProgram";
db.query(query, [name], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, formatPrograms(res));
}
});
}
function formatPrograms(res) {
let obj = {};
let programs = [];
if (res.length > 0) {
obj.id = res[0].id;
obj.name = res[0].name;
obj.Kilograms = res[0].Kilograms;
obj.Pounds = res[0].Pounds;
for (let i of res) {
let program = {};
program.id = i.idProgram;
program.name = i.programName;
program.temperature = i.temperature;
program.time = i.time;
program.centrifuge = i.centrifuge;
program.prewash = i.prewash;
program.wash = i.wash;
program.rinse = i.rinse;
programs.push(program);
}
obj.programs = programs;
return obj;
} else
return res;
}
module.exports = {
getAll,
getPrograms
};
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Oct 29, 2017 at 03:56 PM
-- Server version: 10.1.25-MariaDB
-- PHP Version: 7.1.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `appliance`
--
-- --------------------------------------------------------
--
-- Table structure for table `capacities`
--
CREATE TABLE `capacities` (
`id` int(11) NOT NULL,
`weightKgs` int(11) NOT NULL,
`weightLbs` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `capacities`
--
INSERT INTO `capacities` (`id`, `weightKgs`, `weightLbs`) VALUES
(1, 5, 11),
(2, 7, 15),
(3, 8, 18),
(4, 10, 22);
-- --------------------------------------------------------
--
-- Table structure for table `centrifuges`
--
CREATE TABLE `centrifuges` (
`id` int(11) NOT NULL,
`rpm` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `centrifuges`
--
INSERT INTO `centrifuges` (`id`, `rpm`) VALUES
(1, 400),
(2, 800),
(3, 1000),
(4, 0);
-- --------------------------------------------------------
--
-- Table structure for table `models`
--
CREATE TABLE `models` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`capacity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `models`
--
INSERT INTO `models` (`id`, `name`, `capacity`) VALUES
(1, 'E44JTSB7', 1),
(2, '7VFJS47S', 3);
-- --------------------------------------------------------
--
-- Table structure for table `models_programs`
--
CREATE TABLE `models_programs` (
`idModel` int(11) NOT NULL,
`idProgram` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `models_programs`
--
INSERT INTO `models_programs` (`idModel`, `idProgram`) VALUES
(1, 1),
(1, 2),
(1, 3),
(1, 4),
(1, 7),
(1, 8),
(1, 9),
(2, 1),
(2, 2),
(2, 3),
(2, 4),
(2, 5),
(2, 7),
(2, 8),
(2, 9);
-- --------------------------------------------------------
--
-- Table structure for table `powerstates`
--
CREATE TABLE `powerstates` (
`id` tinyint(1) NOT NULL,
`name` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `powerstates`
--
INSERT INTO `powerstates` (`id`, `name`) VALUES
(0, 'OFF'),
(1, 'ON');
-- --------------------------------------------------------
--
-- Table structure for table `programs`
--
CREATE TABLE `programs` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`temperature` int(11) DEFAULT NULL,
`time` time NOT NULL,
`defaultCentrifuge` int(11) NOT NULL,
`prewash` tinyint(1) NOT NULL,
`wash` tinyint(1) NOT NULL,
`rinse` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `programs`
--
INSERT INTO `programs` (`id`, `name`, `temperature`, `time`, `defaultCentrifuge`, `prewash`, `wash`, `rinse`) VALUES
(1, 'Centrifuge', NULL, '00:30:00', 3, 0, 0, 0),
(2, 'Wool', 30, '00:45:00', 1, 0, 1, 1),
(3, 'Cold', NULL, '01:00:00', 3, 0, 1, 1),
(4, 'Synthetic', 30, '01:20:00', 3, 0, 1, 1),
(5, 'Fast 29\'', 30, '00:29:00', 3, 0, 1, 1),
(6, 'Prewash', 60, '00:20:00', 3, 1, 0, 0),
(7, 'Cotton 90°', 90, '00:50:00', 3, 0, 1, 1),
(8, 'Cotton 60°', 60, '01:10:00', 3, 0, 1, 1),
(9, 'Cotton 40°', 40, '01:30:00', 3, 0, 1, 1);
-- --------------------------------------------------------
--
-- Table structure for table `states`
--
CREATE TABLE `states` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `states`
--
INSERT INTO `states` (`id`, `name`) VALUES
(1, 'paused'),
(2, 'running'),
(3, 'waiting');
-- --------------------------------------------------------
--
-- Table structure for table `units`
--
CREATE TABLE `units` (
`id` int(11) NOT NULL,
`model` int(11) NOT NULL,
`powerState` tinyint(1) NOT NULL DEFAULT '0',
`state` int(11) NOT NULL DEFAULT '3',
`currentProgram` int(11) NOT NULL DEFAULT '9',
`timer` time NOT NULL DEFAULT '00:00:00',
`centrifuge` int(11) NOT NULL DEFAULT '4',
`intensive` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `units`
--
INSERT INTO `units` (`id`, `model`, `powerState`, `state`, `currentProgram`, `timer`, `centrifuge`, `intensive`) VALUES
(2, 2, 0, 3, 5, '00:00:00', 4, 0),
(3, 1, 0, 3, 9, '00:00:00', 4, 0),
(4, 2, 1, 2, 4, '00:00:00', 2, 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `capacities`
--
ALTER TABLE `capacities`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `centrifuges`
--
ALTER TABLE `centrifuges`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `models`
--
ALTER TABLE `models`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`),
ADD KEY `capacity` (`capacity`);
--
-- Indexes for table `models_programs`
--
ALTER TABLE `models_programs`
ADD UNIQUE KEY `index_name` (`idModel`,`idProgram`),
ADD KEY `idProgram` (`idProgram`);
--
-- Indexes for table `powerstates`
--
ALTER TABLE `powerstates`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `programs`
--
ALTER TABLE `programs`
ADD PRIMARY KEY (`id`),
ADD KEY `defaultCentrifuge` (`defaultCentrifuge`);
--
-- Indexes for table `states`
--
ALTER TABLE `states`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `units`
--
ALTER TABLE `units`
ADD PRIMARY KEY (`id`),
ADD KEY `model` (`model`),
ADD KEY `powerState` (`powerState`),
ADD KEY `state` (`state`),
ADD KEY `currentProgram` (`currentProgram`,`model`),
ADD KEY `centrifuge` (`centrifuge`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `capacities`
--
ALTER TABLE `capacities`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `centrifuges`
--
ALTER TABLE `centrifuges`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `models`
--
ALTER TABLE `models`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `programs`
--
ALTER TABLE `programs`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `states`
--
ALTER TABLE `states`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `units`
--
ALTER TABLE `units`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `models_programs`
--
ALTER TABLE `models_programs`
ADD CONSTRAINT `models_programs_ibfk_1` FOREIGN KEY (`idModel`) REFERENCES `models` (`id`),
ADD CONSTRAINT `models_programs_ibfk_2` FOREIGN KEY (`idProgram`) REFERENCES `programs` (`id`);
--
-- Constraints for table `programs`
--
ALTER TABLE `programs`
ADD CONSTRAINT `programs_ibfk_1` FOREIGN KEY (`defaultCentrifuge`) REFERENCES `centrifuges` (`id`);
--
-- Constraints for table `units`
--
ALTER TABLE `units`
ADD CONSTRAINT `units_ibfk_1` FOREIGN KEY (`model`) REFERENCES `models` (`id`),
ADD CONSTRAINT `units_ibfk_3` FOREIGN KEY (`powerState`) REFERENCES `powerstates` (`id`),
ADD CONSTRAINT `units_ibfk_4` FOREIGN KEY (`state`) REFERENCES `states` (`id`),
ADD CONSTRAINT `units_ibfk_5` FOREIGN KEY (`currentProgram`) REFERENCES `programs` (`id`),
ADD CONSTRAINT `units_ibfk_6` FOREIGN KEY (`currentProgram`,`model`) REFERENCES `models_programs` (`idProgram`, `idModel`),
ADD CONSTRAINT `units_ibfk_7` FOREIGN KEY (`centrifuge`) REFERENCES `centrifuges` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>let express = require('express');
let controller = require('../controllers/reset.controller');
let reset = express.Router();
reset.get('/', controller.reset);
module.exports = reset;<file_sep>let express = require('express');
let controller = require('../controllers/models.controller');
let models = express.Router();
models.get('/', controller.getAll);
models.get('/:name', controller.getPrograms);
module.exports = models;<file_sep>let model = require('../dataAccesses/models.dataAccess');
let validator = require('../methods/validate.method');
function getAll(req, res) {
model.getAll((err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
}
else if (result.length === 0) {
res.status(404).send({success: false, message: 'No models found'});
} else {
res.status(200).send({success: true, models: result});
}
});
}
function getPrograms(req, res) {
let name = req.params.name;
if (validator.validateString(name)) {
model.getPrograms(name, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
}
else if (result.length === 0) {
res.status(404).send({success: false, message: 'Model not found'});
} else {
res.status(200).send({success: true, model: result});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
module.exports = {
getAll,
getPrograms
};<file_sep>let model = require('../dataAccesses/units.dataAccess');
let validator = require('../methods/validate.method');
function getAll(req, res) {
model.getAll((err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
}
else if (result.length === 0) {
res.status(404).send({success: false, message: 'No units found'});
} else {
res.status(200).send({success: true, units: result});
}
});
}
function createNew(req, res) {
let idModel = req.body.model;
if (validator.validateInt(idModel)) {
model.createNew(idModel, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Model not found'});
else
res.status(201).send({success: true, message: 'Unit added, with ' + result.insertId + " as 'id'"});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function powerOn(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.powerOn(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The unit was already powered ON'});
else
res.status(200).send({success: true, message: 'Powered ON'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function powerOff(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.powerOff(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The unit was already powered OFF'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot power OFF the unit if its state isn't 'waiting'"
});
else
res.status(200).send({success: true, message: 'Powered OFF'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function run(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.run(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The unit was already running'});
else
res.status(200).send({success: true, message: "State set to 'running'"});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function pause(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.pause(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The unit was already paused'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot pause the unit if its state isn't 'running'"
});
else
res.status(200).send({success: true, message: "State set to 'paused'"});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function wait(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.wait(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The unit was already waiting'});
else
res.status(200).send({success: true, message: "State set to 'waiting'"});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function setProgram(req, res) {
let id = req.params.id;
let program = req.body.program;
if (validator.validateInt(id) && validator.validateInt(program)) {
model.setProgram(id, program, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The program was already set'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot set the unit's current program if its state isn't 'waiting'"
});
else if (result == 406)
res.status(406).send({success: false, message: "Program unavailable for unit's model"});
else
res.status(200).send({success: true, message: 'Program set'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function setCentrifuge(req, res) {
let id = req.params.id;
let centrifuge = req.body.centrifuge;
if (validator.validateInt(id) && validator.validateInt(centrifuge)) {
model.setCentrifuge(id, centrifuge, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The centrifuge was already set'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot set the unit's centrifuge if its state isn't 'waiting'"
});
else if (result == 406)
res.status(406).send({success: false, message: "Centrifuge not valid"});
else
res.status(200).send({success: true, message: 'Centrifuge set'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function setTimer(req, res) {
let id = req.params.id;
let minutes = req.body.minutes;
if (validator.validateInt(id) && validator.validateInt(minutes)) {
model.setTimer(id, minutes, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 202)
res.status(202).send({success: true, message: 'The timer was already set'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot set the unit's timer while it is 'running'"
});
else
res.status(200).send({success: true, message: 'Timer set'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function toggleIntensive(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.toggleIntensive(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else if (result == 403)
res.status(403).send({
success: false,
message: "You cannot toggle 'intensive' if the unit's state isn't 'waiting'"
});
else
res.status(200).send({success: true, message: 'Intensive toggled'});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
function deleteUnit(req, res) {
let id = req.params.id;
if (validator.validateInt(id)) {
model.deleteUnit(id, (err, result) => {
if (err) {
res.status(500).send({success: false, message: 'Internal server error'});
} else {
if (result == 404)
res.status(404).send({success: false, message: 'Unit not found'});
else
res.status(200).send({success: true, message: "Unit deleted"});
}
});
} else
res.status(400).send({success: false, message: 'Bad Request'});
}
module.exports = {
getAll,
createNew,
powerOn,
powerOff,
run,
pause,
wait,
setProgram,
setCentrifuge,
setTimer,
toggleIntensive,
deleteUnit
};<file_sep>let express = require('express');
let controller = require('../controllers/centrifuges.controller');
let models = express.Router();
models.get('/', controller.getAll);
module.exports = models;<file_sep>let model = require('../dataAccesses/reset.dataAccess');
function reset(req, res) {
model.reset((err, result) => {
if (err) {
res.status(500).send({ success: false, message: 'Internal server error' });
} else {
res.status(205).send({ success: true, message: 'Database cleanded' });
}
});
}
module.exports = {
reset
};<file_sep># Appliance
This is an example of an implementation in **NodeJS** of a backend service used to control an appliance such as a washing machine.
### Installation
##### Requirements
* [Node.js](https://nodejs.org/) v8.2.1+
* npm v5.3.0+
* MySQL environment such as [XAMPP](https://www.apachefriends.org/index.html) if on Windows
First create a database called "**appliance**" and import the strucure from the file "**appliance.sql**" found in the root folder of the project.
Modify the **./config/mysql.config.js** file according to your MySQL environment, setting the host address, the user and the password.
```javascript
const parameters={
host: 'localhost',
user: 'root',
password: '',
database: 'appliance'
};
```
Check if you are running **npm** in development environment
```sh
$ npm config get production
```
It should return **false**, if not set it with:
```sh
$ npm config set -g production false
```
Install the dependencies and start the server, it will run on **localhost:3000**
```sh
$ cd Appliance
$ npm install
$ npm start
```
Run the unit test from another console window
```sh
$ npm test
```
It should pass **43** tests.
### Routes
For executing the API calls manually, I suggest using [Postman](https://www.getpostman.com/)
##### Reset
* Reset database to its initial state:
* GET http://localhost:3000/reset
##### Models
* List of available washing machines models:
* GET http://localhost:3000/models
* List of available programs for a certain model
* GET http://localhost:3000/models/:modelName (e.g. http://localhost:3000/models/E44JTSB7)
##### Centrifuges
* List of valid centrifuge rpm parameters (for all models):
* GET http://localhost:3000/centrifuges
##### Units
* List of instantiated units:
* GET http://localhost:3000/units
* Power ON an individual unit:
* GET http://localhost:3000/units/powerOn/:id (e.g. http://localhost:3000/units/powerOn/2)
* Power OFF an individual unit:
* GET http://localhost:3000/units/powerOff/:id (e.g. http://localhost:3000/units/powerOff/2)
* Set state to "running" of an individual unit:
* GET http://localhost:3000/units/run/:id (e.g. http://localhost:3000/units/run/2)
* Set state to "paused" of an individual unit:
* GET http://localhost:3000/units/pause/:id (e.g. http://localhost:3000/units/pause/2)
* Set state to "waiting" of an individual unit:
* GET http://localhost:3000/units/wait/:id (e.g. http://localhost:3000/units/wait/2)
* Add a new unit of a certain model:
* POST http://localhost:3000/units/
* Headers ("Content-Type: application/x-www-form-urlencoded")
* Params ("model: idModel") (a valid model id can be seen from previous request (GET http://localhost:3000/models) )
* Set program to an individual unit:
* PATCH http://localhost:3000/units/program/:id
* Headers ("Content-Type: application/x-www-form-urlencoded")
* Params ("program: idProgram") (a valid program id can be seen from previous request (GET http://localhost:3000/models/:modelName) )
* Set timer to an individual unit:
* PATCH http://localhost:3000/units/timer/:id
* Headers ("Content-Type: application/x-www-form-urlencoded")
* Params ("minutes: amountOfMinutes")
* Toggle "intensive" of an individual unit:
* GET http://localhost:3000/units/toggleIntensive/:id (e.g. http://localhost:3000/units/toggleIntensive/2)
* Delete the instance of an individual unit:
* DELETE http://localhost:3000/units/delete/:id (e.g. http://localhost:3000/units/delete/2)
<file_sep>let db = require('../config/mysql.config').db;
let request = require('request');
function getAll(callback) {
let query = "SELECT u.id, m.name as model, p.name as powerState, s.name as state, c.name as currentProgram, u.timer, f.rpm as centrifuge, u.intensive " +
"FROM units u, models m, powerstates p, states s, programs c, centrifuges f " +
"WHERE u.model=m.id AND u.powerState=p.id AND u.state=s.id AND u.currentProgram=c.id AND u.centrifuge=f.id " +
"ORDER BY u.id";
db.query(query, (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
function createNew(idModel, callback) {
let query1 = "SELECT `id` FROM `models` WHERE id=?"
let query2 = "INSERT INTO units (model) " +
"VALUES (?);";
db.query(query1, [idModel], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else
db.query(query2, [idModel], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function powerOn(id, callback) {
let query1 = "SELECT `id`, `powerState`, `state` FROM `units` WHERE id=?"
let query2 = "UPDATE units SET powerState=1 " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].powerState == 1)
return callback(null, 202);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function powerOff(id, callback) {
let query1 = "SELECT `id`, `powerState`, `state` FROM `units` WHERE id=?"
let query2 = "UPDATE units SET powerState=0 " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].powerState == 0)
return callback(null, 202);
else if (res[0] && res[0].state != 3)
return callback(null, 403);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function run(id, callback) {
let query1 = "SELECT `id`, `powerState`, `state` FROM `units` WHERE id=?"
let query2 = "UPDATE units SET state=2 " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].state == 2)
return callback(null, 202);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function pause(id, callback) {
let query1 = "SELECT `id`, `powerState`, `state` FROM `units` WHERE id=?"
let query2 = "UPDATE units SET state=1 " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].state == 1)
return callback(null, 202);
else if (res[0] && res[0].state != 2)
return callback(null, 403);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function wait(id, callback) {
let query1 = "SELECT `id`, `powerState`, `state` FROM `units` WHERE id=?"
let query2 = "UPDATE units SET state=3 " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].state == 3)
return callback(null, 202);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function setProgram(id, program, callback) {
let query1 = "SELECT `id`, `model`, `state`, `currentProgram` FROM `units` WHERE id=?";
let query2 = "SELECT m.idModel, m.idProgram, p.defaultCentrifuge " +
"FROM models_programs m JOIN programs p ON m.idProgram=p.id " +
"WHERE m.idModel=? AND m.idProgram=?";
let query3 = "UPDATE units SET currentProgram=?, centrifuge=? " +
"WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].currentProgram == program)
return callback(null, 202);
else if (res[0] && res[0].state != 3)
return callback(null, 403);
else
db.query(query2, [res[0].model, program], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 406);
db.query(query3, [program, res[0].defaultCentrifuge, id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
});
}
function setCentrifuge(id, centrifuge, callback) {
let query1 = "SELECT `id`, `model`, `state`, `centrifuge` FROM `units` WHERE id=?";
let query2 = "SELECT id FROM centrifuges WHERE id=?";
let query3 = "UPDATE units SET centrifuge=? WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].centrifuge == centrifuge)
return callback(null, 202);
else if (res[0] && res[0].state != 3)
return callback(null, 403);
else
db.query(query2, [centrifuge], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 406);
db.query(query3, [centrifuge, id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
});
}
function setTimer(id, minutes, callback) {
let query1 = "SELECT `id`, `state`, TIME_TO_SEC(timer)/60 as timer FROM `units` WHERE id=?";
let query2 = "UPDATE units SET timer=SEC_TO_TIME(?*60) WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].timer == minutes)
return callback(null, 202);
else if (res[0] && res[0].state == 2)
return callback(null, 403);
else
db.query(query2, [minutes, id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function toggleIntensive(id, callback) {
let query1 = "SELECT `id`, `state`, `intensive` FROM `units` WHERE id=?"
let query2 = "UPDATE `units` SET `intensive`=? WHERE id=?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else if (res[0] && res[0].state != 3)
return callback(null, 403);
else
db.query(query2, [!res[0].intensive, id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
function deleteUnit(id, callback) {
let query1 = "SELECT `id` FROM `units` WHERE id=?"
let query2 = "DELETE FROM units WHERE id = ?";
db.query(query1, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
if (res.length == 0)
return callback(null, 404);
else
db.query(query2, [id], (err, res) => {
if (err) {
console.log(err);
return callback(err);
} else {
return callback(null, res);
}
});
}
});
}
module.exports = {
getAll,
createNew,
powerOn,
powerOff,
run,
pause,
wait,
setProgram,
setCentrifuge,
setTimer,
toggleIntensive,
deleteUnit
};
<file_sep>let model = require('../dataAccesses/centrifuges.dataAccess');
function getAll(req, res) {
model.getAll((err, result) => {
if (err) {
res.status(500).send({ success: false, message: 'Internal server error' });
}
else if (result.length === 0) {
res.status(404).send({ success: false, message: 'No centrifuges found' });
} else {
res.status(200).send({ success: true, centrifuges: result });
}
});
}
module.exports = {
getAll
};<file_sep>let expect = require('chai').expect;
let request = require('request');
describe('Reset', function (done) {
this.timeout(5000);
it('Clean Database', function (done) {
request('http://localhost:3000/reset', function (error, response, body) {
expect(response.statusCode).to.equal(205);
done();
});
});
});
describe('Models', function (done) {
it('Get all models', function (done) {
request('http://localhost:3000/models', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it("Model's Programs", function (done) {
request('http://localhost:3000/models/E44JTSB7', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Centrifuges', function (done) {
it('List of valid centrifuges', function (done) {
request('http://localhost:3000/centrifuges', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Units', function (done) {
it('List of all units', function (done) {
request('http://localhost:3000/units', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
describe('Power ON', function (done) {
it('Power ON nonexistent unit', function (done) {
request('http://localhost:3000/units/powerOn/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Power ON if OFF', function (done) {
request('http://localhost:3000/units/powerOn/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('Power ON if ON', function (done) {
request('http://localhost:3000/units/powerOn/2', function (error, response, body) {
expect(response.statusCode).to.equal(202);
done();
});
});
});
describe('Power OFF', function (done) {
it('Power OFF nonexistent unit', function (done) {
request('http://localhost:3000/units/powerOff/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Power OFF if ON', function (done) {
request('http://localhost:3000/units/powerOff/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('Power OFF if OFF', function (done) {
request('http://localhost:3000/units/powerOff/2', function (error, response, body) {
expect(response.statusCode).to.equal(202);
done();
});
});
it('Power OFF when running or paused', function (done) {
request('http://localhost:3000/units/powerOff/4', function (error, response, body) {
expect(response.statusCode).to.equal(403);
done();
});
});
});
describe('Run', function (done) {
it('Run nonexistent unit', function (done) {
request('http://localhost:3000/units/run/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Run when not running', function (done) {
request('http://localhost:3000/units/run/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('Run when running', function (done) {
request('http://localhost:3000/units/run/2', function (error, response, body) {
expect(response.statusCode).to.equal(202);
done();
});
});
});
describe('Pause', function (done) {
it('Pause nonexistent unit', function (done) {
request('http://localhost:3000/units/pause/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Pause when running', function (done) {
request('http://localhost:3000/units/pause/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('Pause when paused', function (done) {
request('http://localhost:3000/units/pause/2', function (error, response, body) {
expect(response.statusCode).to.equal(202);
done();
});
});
it('Pause when waiting', function (done) {
request('http://localhost:3000/units/pause/3', function (error, response, body) {
expect(response.statusCode).to.equal(403);
done();
});
});
});
describe('Wait', function (done) {
it('Wait nonexistent unit', function (done) {
request('http://localhost:3000/units/wait/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Wait when not waiting', function (done) {
request('http://localhost:3000/units/wait/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
it('Wait when waiting', function (done) {
request('http://localhost:3000/units/wait/2', function (error, response, body) {
expect(response.statusCode).to.equal(202);
done();
});
});
});
describe('Add Unit', function (done) {
it('Add nonexistent model', function (done) {
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units',
body: "model=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(404);
done();
});
});
it('Add model', function (done) {
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units',
body: "model=1"
}, function(error, response, body){
expect(response.statusCode).to.equal(201);
done();
});
});
});
describe('Program', function (done) {
it('Set program nonexistent unit', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/program/55',
body: "program=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(404);
done();
});
});
it('Set program already set', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/program/3',
body: "program=9"
}, function(error, response, body){
expect(response.statusCode).to.equal(202);
done();
});
});
it('Set program when not waiting', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/program/4',
body: "program=9"
}, function(error, response, body){
expect(response.statusCode).to.equal(403);
done();
});
});
it('Set unavailable program for unit', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/program/3',
body: "program=5"
}, function(error, response, body){
expect(response.statusCode).to.equal(406);
done();
});
});
it('Set program', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/program/3',
body: "program=4"
}, function(error, response, body){
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Centrifuge', function (done) {
it('Set centrifuge nonexistent unit', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/centrifuge/55',
body: "centrifuge=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(404);
done();
});
});
it('Set centrifuge already set', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/centrifuge/3',
body: "centrifuge=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(202);
done();
});
});
it('Set centrifuge when not waiting', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/centrifuge/4',
body: "centrifuge=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(403);
done();
});
});
it('Set nonexistent centrifuge', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/centrifuge/3',
body: "centrifuge=5"
}, function(error, response, body){
expect(response.statusCode).to.equal(406);
done();
});
});
it('Set centrifuge', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/centrifuge/3',
body: "centrifuge=2"
}, function(error, response, body){
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Timer', function (done) {
it('Set timer nonexistent unit', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/timer/55',
body: "minutes=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(404);
done();
});
});
it('Set timer already set', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/timer/3',
body: "minutes=0"
}, function(error, response, body){
expect(response.statusCode).to.equal(202);
done();
});
});
it('Set timer when running', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/timer/4',
body: "minutes=3"
}, function(error, response, body){
expect(response.statusCode).to.equal(403);
done();
});
});
it('Set timer', function (done) {
request.patch({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:3000/units/timer/3',
body: "minutes=5"
}, function(error, response, body){
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Toggle Intensive', function (done) {
it('Toggle intensive nonexistent unit', function (done) {
request('http://localhost:3000/units/toggleIntensive/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Toggle intensive when running or paused', function (done) {
request('http://localhost:3000/units/toggleIntensive/4', function (error, response, body) {
expect(response.statusCode).to.equal(403);
done();
});
});
it('Toggle intensive', function (done) {
request('http://localhost:3000/units/toggleIntensive/2', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
});
describe('Delete Unit', function (done) {
it('Delete nonexistent unit', function (done) {
request.delete('http://localhost:3000/units/delete/55', function (error, response, body) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('Delete', function (done) {
request.delete('http://localhost:3000/units/delete/5', function (error, response, body) {
expect(response.statusCode).to.equal(200);
done();
});
});
});
}); | 4b8742bd7f38ad6d4731e652b5225534c0a7afec | [
"JavaScript",
"SQL",
"Markdown"
] | 12 | JavaScript | Yaro96/Appliance | fcda8b8922600a8fbdea6f60e6a18092d2b287ec | c2701216b55c8de09ba0855486232cbbdcc5f68f |
refs/heads/master | <file_sep>'use strict';
process.env.PATH = `${process.env.PATH}:${process.env.LAMBDA_TASK_ROOT}`;
const Alexa = require('alexa-sdk');
const newSessionHandlers = require('./handlers/new-session.handlers');
const stoppedHandlers = require('./handlers/stopped.handlers');
module.exports.handler = function (event, context) {
const alexa = Alexa.handler(event, context);
alexa.appId = event.session.application.applicationId;
alexa.registerHandlers(
newSessionHandlers,
stoppedHandlers
);
alexa.execute();
};
<file_sep># Alexa Starter Kit
A bare bones app to fill in with your ingenious skill<file_sep>module.exports.GAME_STATES = {
STOPPED: 'STOPPED',
};
<file_sep>/* eslint-disable max-len */
const assert = require('assert');
const skill = require('../index');
const context = require('aws-lambda-mock-context');
const sessionStartIntent = require('./event-samples/new-session/session-start.intent');
const {
keepGoing,
goodbye,
yesOrNo,
} = require('../responses');
const { GAME_STATES } = require('../enums');
const sanitise = text => text.replace(/\n/g, '');
const getOutputSpeech = ({ response: { outputSpeech: { ssml } } }) =>
sanitise(ssml).match(/<speak>(.*)<\/speak>/i)[1].trim();
const getAttribute = ({ sessionAttributes }, attr) => sessionAttributes[attr];
const runIntent = intent => new Promise(res => {
const ctx = context();
skill.handler(intent, ctx);
ctx
.Promise
.then(obj => {
// console.log(obj);
res({
endOfSession: obj.response.shouldEndSession,
outputSpeech: getOutputSpeech(obj),
gameState: getAttribute(obj, 'STATE'),
});
})
.catch(err => {
throw new Error(err);
});
});
describe('Alexa, start game', () => {
it('Did your skill do what it was supposed to...?', () =>
runIntent(sessionStartIntent)
.then(({ outputSpeech, gameState }) => {
// assert.deepEqual(outputSpeech, sanitise(welcome()));
// assert.deepEqual(gameState, GAME_STATES.SOME_STATE);
}));
});
<file_sep>'use strict';
const GAME_STATES = require('../enums').GAME_STATES;
const setStateAndInvokeEntryIntent = function() {
// updates
// this.handler.state = GAME_STATES.SOME_STATE;
// response
// this.emitWithState('SomeIntent');
};
module.exports = {
NewSession() {
setStateAndInvokeEntryIntent.call(this);
},
LaunchRequest() {
setStateAndInvokeEntryIntent.call(this);
},
Unhandled() {
console.log('unhandled');
},
};
| d4c78e612a6a101a055f50d995b475a6675f8dec | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | tillreiter/alexa-kompliment-skill | 03d87a598701e2f51442605734c5efd05bbf0d7c | f3e715db5fa80726d0e2da91cc316cd24eb032f1 |
refs/heads/master | <repo_name>aibou/rodgers<file_sep>/bin/rodgers
#!/usr/bin/env ruby
$: << File.expand_path("#{File.dirname __FILE__}/../lib")
require 'rodgers'
SlackRubyBot::Client.logger.level = Logger::INFO
Rodgers.start
<file_sep>/lib/rodgers/controller.rb
# コマンド書く
# ActiveSupport::Callbacks でException周りをハンドルする
module Rodgers
class Controller < SlackRubyBot::MVC::Controller::Base
def ping
view.say(channel: data.channel, text: "pong")
end
def ip
account_name, search_name, *_ = match["expression"].split(/\s+/)
account_id = fetch_account_id(account_name)
credentials = assume_role_credentials(account_id)
aws_client = Aws::EC2::Client.new(region: 'ap-northeast-1', credentials: credentials)
hosts = []
instances = aws_client.describe_instances(
filters: [
{
name: "tag:opsworks:instance",
values: ["*#{search_name}*"]
}
]
).reservations.map(&:instances).flatten
instances.each do |ec2|
hosts << {
private_ip: ec2.private_ip_address,
hostname: Hash[*ec2.tags.map{|tag|[tag.key,tag.value]}.flatten]["opsworks:instance"],
}
end
hosts.sort! do |v1, v2|
v1[:hostname] <=> v2[:hostname]
end
view.format_as_code_block(hosts, length: 20, without_key: true)
end
def tag
args = match["expression"].split(/\s+/)
case args[0]
when /^arn:/
arn, tag_name, tag_value, *_ = args
# 両方共nilの場合はそのARNについているtag一覧を表示
# memo: 現状、resourcegroupstaggingapi に ARN指定するオプションがない
# そのため、[serviceのtag APIを使う] か [rgta:GetResourcesをフィルタするか] の2択
# 前者のほうが高速だが、clientとactionを変えるのが面倒、後者はpaginationのためワーストケースがかなり遅い
if [tag_name, tag_value].all?(&:nil?)
service, region, account_id, *resource_names = arn.split(/:/)[2..-1]
credentials = assume_role_credentials(account_id)
aws_client = Aws::ResourceGroupsTaggingAPI::Client.new(region: region, credentials: credentials)
page_token, tags = nil
loop do
resources = aws_client.get_resources(resource_type_filters: [service], starting_token: page_token).resource_tag_mapping_list
if resources.any? {|e| e.resource_arn == arn }
tags = resources.find{|e| e.resource_arn == arn }.tags
break
end
break if resources.pagination_token.empty?
end
view.format_as_code_block(tags.map{|e| {key: e.key, value: e.value}} , length: 32, without_key: true)
return
end
# いずれかがnilの場合(というかtag_valueがnilの場合)はエラー
if [tag_name, tag_value].any?(&:nil?)
view.say(
text: "Too short args.",
channel: data.channel
)
end
service, region, account_id, *resource_names = arn.split(/:/)[2..-1]
resource_name = resource_names.join(':')
credentials = assume_role_credentials(account_id)
aws_client = Aws::ResourceGroupsTaggingAPI::Client.new(region: region, credentials: credentials)
resp = aws_client.tag_resources(resource_arn_list: [arn], tags: Hash[tag_name, tag_value])
if resp.failed_resources_map.empty?
view.say(
text: "Tag attached to #{resource_name} on #{service}",
channel: data.channel
)
else
view.say(
text: "Failed to attach tags to #{resource_name} on #{service}. #{resp.failed_resources_map}",
channel: data.channel
)
end
end
end
def rdsip
account_name, search_name, *_ = match["expression"].split(/\s+/)
account_id = fetch_account_id(account_name)
credentials = assume_role_credentials(account_id)
begin
rds_client = Aws::RDS::Client.new(region: 'ap-northeast-1', credentials: credentials)
rdses = rds_client.describe_db_instances.db_instances.select{|rds|rds.db_instance_identifier =~ /#{search_name}/}
hosts = rdses.map do |rds|
ip = Resolv.getaddress(rds.endpoint.address)
if [IPAddr.new('10.0.0.0/8'), IPAddr.new('172.16.0.0/12'), IPAddr.new('192.168.0.0/16')].any?{|private_cidr| private_cidr.include? ip}
{ private_ip: ip, db_instance_identifier: rds.db_instance_identifier }
else
ec2_client = Aws::EC2::Client.new(region: 'ap-northeast-1', credentials: credentials)
private_ip = ec2_client.describe_network_interfaces(filters: [{name: 'association.public-ip', values: [ip]}]).network_interfaces[0].private_ip_address
{ private_ip: private_ip, db_instance_identifier: rds.db_instance_identifier }
end
end
rescue Aws::RDS::Errors::AccessDenied => e
view.error("Oops, got error", e)
rescue Aws::EC2::Errors::AccessDenied => e
view.error("Oops, got error", e)
end
view.format_as_code_block(hosts, length: 20, without_key: true)
end
private
def assume_role_credentials(account_id)
begin
Aws::AssumeRoleCredentials.new(
client: Aws::STS::Client.new(region: 'ap-northeast-1', credentials: Aws::CredentialProviderChain.new.resolve),
role_arn: "arn:aws:iam::#{account_id}:role/#{ENV["ASSUME_ROLE_NAME"]}",
role_session_name: 'rodgers'
)
rescue Aws::STS::Errors::AccessDenied
view.error("Oops, denied assume_role to arn:aws:iam::#{account_id}:role/#{ENV["ASSUME_ROLE_NAME"]}", nil)
end
end
def fetch_account_id(account_name)
begin
ssm_client = Aws::SSM::Client.new(region: 'ap-northeast-1', credentials: Aws::CredentialProviderChain.new.resolve)
ssm_client.get_parameter(name: "#{account_name}.account_id").parameter.value
rescue Aws::SSM::Errors::ParameterNotFound
view.error("Not found '#{account}.account_id' in SSM ParameterStore. please store it to AWS in account id: #{Aws::STS::Client.new().get_caller_identity.account}", nil)
end
end
end
end
<file_sep>/lib/rodgers.rb
require 'slack-ruby-bot'
require 'aws-sdk'
require 'erb'
require 'resolv'
require 'ipaddr'
require 'rodgers/controller'
require 'rodgers/view'
require 'rodgers/model'
require 'rodgers/bot'
module Rodgers
def self.start
Bot.run
end
end
<file_sep>/lib/rodgers/view.rb
module Rodgers
class View < SlackRubyBot::MVC::View::Base
def format_as_code_block(obj, options = {})
say(
channel: data.channel,
text: <<~EOS
```
#{recursive_to_string(obj, options).chomp}
```
EOS
)
end
def error(message, exception)
say(
channel: data.channel,
text: "#{message}. `#{exception}`"
)
end
private
# hashやarrayを再帰でstringにしていく
def recursive_to_string(obj, options = {})
case obj
when String
unless options[:length].nil?
sprintf("%+-#{options[:length]}s",obj)
else
obj
end
when Array
str = obj.map do |e|
recursive_to_string(e, options)
end.join
str << "\n" if obj.all?(String)
str
when Hash
if options[:without_key]
recursive_to_string(obj.values, options)
else
recursive_to_string(obj.map{|k,v|"#{k}: #{v}"}, options)
end
else
end
end
end
end
<file_sep>/lib/rodgers/bot.rb
module Rodgers
class Bot < SlackRubyBot::Bot
@controller = Rodgers::Controller.new(Rodgers::Model.new, Rodgers::View.new)
end
end
<file_sep>/Dockerfile
FROM ruby:2.5.1-alpine
WORKDIR work
ENV RUBY_PACKAGES "ruby ruby-dev ruby-bundler ruby-io-console libffi-dev build-base"
RUN apk --no-cache add $RUBY_PACKAGES
COPY Gemfile /work/Gemfile
COPY Gemfile.lock /work/Gemfile.lock
RUN bundle install -j 2
COPY bin /work/bin
COPY lib /work/lib
ENTRYPOINT ["bundle", "exec", "bin/rodgers"]
<file_sep>/lib/rodgers/model.rb
# AWS SDKの処理ここに書きたい感
module Rodgers
class Model < SlackRubyBot::MVC::Model::Base
end
end
<file_sep>/README.md
Go Pack Go!
# About
AWSのもろもろをSlackBot経由で操作するやつです
[図を入れて解説する]
# Setup
## Push to ECR
## Create Task Role
信頼関係は以下の通りECS Taskのサービスを登録する
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
```
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Resource": [
"arn:aws:iam::[子アカウントのアカウントID]:role/[子アカウントで使うロール名]",
"arn:aws:iam::[子アカウントのアカウントID]:role/[子アカウントで使うロール名]"
]
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameter"
],
"Resource": [
"*"
]
}
]
}
```
> 子アカウントが複数ある場合は、それぞれの子アカウントIDを記載する必要がある。 アカウントID部分に `*` は使えない
> 子アカウントで使うロール名は、子アカウント複数ある場合は同一名称である必要がある。
## Create ECS Task Definition
TODO: ACCOUNT_ROLE_NAME, SLACK_API_TOKEN
## Create ECS Cluster & Services
ここは省略します。
## 子アカウントに親アカウントからassume roleさせるためのロールを作成する
## 親アカウントのEC2 System Manager ParameterStoreでアカウント名とアカウントIDを登録する | 9035909282b5bdf3b5c57e7d6b417e1ece45a6fd | [
"Markdown",
"Ruby",
"Dockerfile"
] | 8 | Ruby | aibou/rodgers | 1d8554a1f6c67e93049dc66e1ccf6437a9369ec3 | 185b221493eff0ea339a9d46b77a6f37217a0dfa |
refs/heads/master | <repo_name>BelkaLab/RaygunBundle<file_sep>/NietonfirRaygunBundle.php
<?php
namespace Nietonfir\RaygunBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class NietonfirRaygunBundle extends Bundle
{
}
<file_sep>/Tests/DependencyInjection/NietonfirRaygunExtensionTest.php
<?php
/*
* This file is part of the Raygunbundle package.
*
* (c) nietonfir <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nietonfir\RaygunBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Nietonfir\RaygunBundle\DependencyInjection\NietonfirRaygunExtension;
use Symfony\Component\Yaml\Parser;
class NietonfirRaygunExtensionTest extends \PHPUnit_Framework_TestCase
{
/** @var ContainerBuilder */
protected $configuration;
public function testDefaults()
{
$this->configuration = new ContainerBuilder();
$loader = new NietonfirRaygunExtension();
$config = $this->getEmptyConfig();
$loader->load(array($config), $this->configuration);
$this->assertAlias('nietonfir_raygun.client', 'raygun.client');
$this->assertAlias('nietonfir_raygun.monolog_handler', 'raygun.handler');
$this->assertParameter('1234567', 'nietonfir_raygun.api_key');
$this->assertParameter(true, 'nietonfir_raygun.async');
$this->assertParameter(false, 'nietonfir_raygun.debug_mode');
$this->assertParameter(false, 'nietonfir_raygun.disable_user_tracking');
$this->assertHasDefinition('nietonfir_raygun.monolog_handler');
$this->assertHasDefinition('nietonfir_raygun.twig_extension');
}
public function testCustomSettings()
{
$this->configuration = new ContainerBuilder();
$loader = new NietonfirRaygunExtension();
$config = $this->getFullConfig();
$loader->load(array($config), $this->configuration);
$this->assertAlias('nietonfir_raygun.client', 'raygun.client');
$this->assertAlias('nietonfir_raygun.monolog_handler', 'raygun.handler');
$this->assertParameter('987655', 'nietonfir_raygun.api_key');
$this->assertParameter(false, 'nietonfir_raygun.async');
$this->assertParameter(true, 'nietonfir_raygun.debug_mode');
$this->assertParameter(true, 'nietonfir_raygun.disable_user_tracking');
$this->assertHasDefinition('nietonfir_raygun.monolog_handler');
$this->assertHasDefinition('nietonfir_raygun.twig_extension');
$this->assertHasCall('nietonfir_raygun.monolog_handler', 'setIgnore404');
}
/**
* getEmptyConfig
*
* @return array
*/
protected function getEmptyConfig()
{
$yaml = <<<EOF
api_key: 1234567
EOF;
$parser = new Parser();
return $parser->parse($yaml);
}
/**
* getEmptyConfig
*
* @return array
*/
protected function getFullConfig()
{
$yaml = <<<EOF
api_key: 987655
async: false
debug_mode: true
track_users: false
ignore_404: true
EOF;
$parser = new Parser();
return $parser->parse($yaml);
}
/**
* @param string $value
* @param string $key
*/
private function assertAlias($value, $key)
{
$this->assertEquals($value, (string) $this->configuration->getAlias($key), sprintf('%s alias is correct', $key));
}
/**
* @param mixed $value
* @param string $key
*/
private function assertParameter($value, $key)
{
$this->assertEquals($value, $this->configuration->getParameter($key), sprintf('%s parameter is correct', $key));
}
/**
* @param string $id
*/
private function assertHasDefinition($id)
{
$this->assertTrue(($this->configuration->hasDefinition($id) ?: $this->configuration->hasAlias($id)));
}
private function assertHasCall($id, $method)
{
$definition = $this->configuration->getDefinition($id);
$this->assertTrue($definition->hasMethodCall($method));
}
protected function tearDown()
{
unset($this->configuration);
}
}
<file_sep>/Tests/DependencyInjection/ConfigurationTest.php
<?php
/*
* This file is part of the Raygunbundle package.
*
* (c) nietonfir <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nietonfir\RaygunBundle\Tests\DependencyInjection;
use Nietonfir\RaygunBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
public function testProcessDefaultConfig()
{
$key = '1234567';
$configs = array(
array(
'api_key' => $key
)
);
$config = $this->process($configs);
$this->assertArrayHasKey('api_key', $config);
$this->assertArrayHasKey('async', $config);
$this->assertArrayHasKey('debug_mode', $config);
$this->assertArrayHasKey('track_users', $config);
$this->assertArrayHasKey('ignore_404', $config);
$this->assertEquals($key, $config['api_key']);
$this->assertTrue($config['async']);
$this->assertFalse($config['debug_mode']);
$this->assertTrue($config['track_users']);
$this->assertFalse($config['ignore_404']);
}
public function testDebugModeSet()
{
$key = '1234567';
$configs = array(
array(
'api_key' => $key,
'debug_mode' => true
)
);
$config = $this->process($configs);
$this->assertArrayHasKey('async', $config);
$this->assertArrayHasKey('debug_mode', $config);
$this->assertFalse($config['async']);
$this->assertTrue($config['debug_mode']);
}
public function testDisableUserTracking()
{
$key = '1234567';
$configs = array(
array(
'api_key' => $key,
'track_users' => false
)
);
$config = $this->process($configs);
$this->assertArrayHasKey('track_users', $config);
$this->assertFalse($config['track_users']);
}
public function testIgnore404ModeSet()
{
$key = '1234567';
$configs = array(
array(
'api_key' => $key,
'ignore_404' => true
)
);
$config = $this->process($configs);
$this->assertArrayHasKey('ignore_404', $config);
$this->assertTrue($config['ignore_404']);
}
/**
* @expectedException Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidConfig()
{
$configs = array(
array(
'api_key' => null,
'async' => 'blub',
'debug_mode' => 'blub'
)
);
$config = $this->process($configs);
}
/**
* Processes an array of configurations and returns a compiled version similar to
* @see \Symfony\Component\HttpKernel\DependencyInjection\Extension
*
* @param array $configs An array of raw configurations
* @return array A normalized array
*/
protected function process($configs)
{
$processor = new Processor();
return $processor->processConfiguration(new Configuration(), $configs);
}
}
<file_sep>/README.md
RaygunBundle
============
[Raygun4PHP](https://github.com/MindscapeHQ/raygun4php) is a [Raygun.io](https://raygun.io) provider for PHP 5.3+.
[Raygun4js](https://github.com/MindscapeHQ/raygun4js) is a is a [Raygun.io](https://raygun.io) plugin for JavaScript.
This bundle registers the library with the framework and provides a twig template for the plugin.
[](https://packagist.org/packages/nietonfir/raygun-bundle) [](https://packagist.org/packages/nietonfir/raygun-bundle) [](https://github.com/Nietonfir/RaygunBundle/blob/master/LICENSE)
Installation
------------
Install the latest version with
```
$ composer require nietonfir/raygun-bundle
```
Configuration
-------------
Add your raygun api-key in parameters.yml:
```yaml
# app/config/parameters.yml
parameters:
[…]
raygun_api_key: <your_raygun_api-key>
```
Update `config.yml` with the following configuration:
```yaml
# app/config/config.yml
nietonfir_raygun:
api_key: %raygun_api_key%
```
Enable the bundle:
```php
// app/AppKernel.php
$bundles = [
[…]
new Nietonfir\RaygunBundle\NietonfirRaygunBundle(),
];
```
Basic Usage
-----------
Register the raygun monolog handler in `config_prod.yml` as the first monolog handler.
```yaml
# app/config/config_prod.yaml
monolog:
handlers:
raygun:
type: service
id: raygun.handler
main:
type: fingers_crossed
action_level: error
handler: nested
```
To use the [JavaScript client](https://raygun.io/docs/languages/javascript) include the bundled views in your template at their designated places according to the raygun documentation. [`NietonfirRaygunBundle:Static:raygun-js.html.twig`](Resources/views/Static/raygun-js.html.twig) provides the javascript client and [`NietonfirRaygunBundle::setup.html.twig`](Resources/views/setup.html.twig) configures it, e.g.:
```twig
{# snip #}
{% include 'NietonfirRaygunBundle:Static:raygun-js.html.twig' %}
</head>
<body>
{# snip #}
{% include 'NietonfirRaygunBundle::setup.html.twig' %}
</body>
```
If you wish to override any part of the templates you can use the default Symfony mechanisms. A global twig parameter (`raygun_api_key`) is exposed by a custom `Twig_Extension` that provides the API key.
Raygun pulse can be enabled by either setting or passing a truthy variable named `enable_pulse` to the template:
```twig
{% include 'NietonfirRaygunBundle::setup.html.twig' with {'enable_pulse': true} only %}
```
Configuration Reference
-----------------------
```yaml
# app/config/config.yml
nietonfir_raygun:
api_key: %raygun_api_key% # Your Raygun API key, available under "Application Settings" in your Raygun account.
async: true # Sets the [async configuration option](https://github.com/MindscapeHQ/raygun4php#sending-method---asyncsync) on the Raygun client.
debug_mode: false # Sets the [debug configuration option](https://github.com/MindscapeHQ/raygun4php#debug-mode) on the Raygun client.
ignore_404: false # Whether to send 404 exceptions (NotFoundHttpException) to Raygun
```
<file_sep>/Monolog/Handler/RaygunHandler.php
<?php
/*
* This file is part of the Raygunbundle package.
*
* (c) nietonfir <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nietonfir\RaygunBundle\Monolog\Handler;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use Raygun4php\RaygunClient;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class RaygunHandler extends AbstractProcessingHandler
{
protected $client;
/**
* @var bool
*/
private $ignore404 = false;
/**
* @param RaygunClient $client The Raygun.io client responsible for sending errors/exceptions to Raygun
* @param int $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct(RaygunClient $client, $level = Logger::ERROR, $bubble = true)
{
$this->client = $client;
parent::__construct($level, $bubble);
}
/**
* @param bool $ignore404
*/
public function setIgnore404($ignore404)
{
$this->ignore404 = (bool) $ignore404;
}
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
$ctx = $record['context'];
$exception = isset($ctx['exception']) ? $ctx['exception'] : false;
if ($exception) {
if ($this->ignore404 && $exception instanceof NotFoundHttpException) {
return;
}
$this->client->sendException($exception);
} else {
$this->client->sendError($record['level'], $record['message'], $ctx['file'], $ctx['line']);
}
}
/**
* {@inheritdoc}
*/
protected function getDefaultFormatter()
{
return new NormalizerFormatter();
}
}
<file_sep>/DependencyInjection/Configuration.php
<?php
/*
* This file is part of the Raygunbundle package.
*
* (c) nietonfir <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nietonfir\RaygunBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('nietonfir_raygun');
$rootNode
->children()
->scalarNode('api_key')
->isRequired()
->cannotBeEmpty()
->end() // api_key
->booleanNode('async')
->defaultTrue()
->end() // async
->booleanNode('track_users')
->defaultTrue()
->end() // track_users
->booleanNode('debug_mode')
->defaultFalse()
->end() // debug_mode
->booleanNode('ignore_404')
->defaultFalse()
->end() // ignore_404
->end()
->validate()
->ifTrue(function($v){return $v['debug_mode'];})
->then(function($v){$v['async'] = false;return $v;})
->end();
return $treeBuilder;
}
}
<file_sep>/Tests/Monolog/Handler/RaygunHandlerTest.php
<?php
/*
* This file is part of the Raygunbundle package.
*
* (c) nietonfir <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nietonfir\RaygunBundle\Tests\Monolog\Handler;
use Monolog\TestCase;
use Monolog\Logger;
use Nietonfir\RaygunBundle\Monolog\Handler\RaygunHandler;
class RaygunHandlerTest extends TestCase
{
protected $client;
public function setUp()
{
$this->client = $this->getMockBuilder('Raygun4php\RaygunClient')
->disableOriginalConstructor()
->getMock();
}
public function testConstruct()
{
$reflection = new \ReflectionProperty('Nietonfir\RaygunBundle\Monolog\Handler\RaygunHandler', 'client');
$reflection->setAccessible(true);
$handler = new RaygunHandler($this->client);
$this->assertEquals($this->client, $reflection->getValue($handler));
}
public function testHandleError()
{
$record = $this->getRecord(Logger::CRITICAL, 'test', array('file' => __FILE__, 'line' => 42));
$this->client->expects($this->once())
->method('sendError')
->with(
$this->equalTo(Logger::CRITICAL),
$this->equalTo('test'),
$this->equalTo(__FILE__),
$this->equalTo(42)
);
$handler = new RaygunHandler($this->client);
$handler->handle($record);
}
public function testHandleException()
{
$exceptionMock = $this->getMock('Exception');
$record = $this->getRecord(Logger::CRITICAL, 'test', array('exception' => $exceptionMock));
$this->client->expects($this->once())
->method('sendException')
->with($exceptionMock);
$handler = new RaygunHandler($this->client);
$handler->handle($record);
}
public function testIgnore404()
{
$exceptionMock = $this->getMock('Symfony\Component\HttpKernel\Exception\NotFoundHttpException');
$record = $this->getRecord(Logger::CRITICAL, 'test', array('exception' => $exceptionMock));
$this->client->expects($this->never())
->method('sendException');
$handler = new RaygunHandler($this->client);
$handler->setIgnore404(true);
$handler->handle($record);
}
}
| 58308179662e8821d9c54a9b7e94fc38f43eedda | [
"Markdown",
"PHP"
] | 7 | PHP | BelkaLab/RaygunBundle | d6922092eb4444864b5db8ea5f70e49baec3381c | 54c25c3e586695f46eb936f9857c9b41af083f7d |
refs/heads/master | <repo_name>SaiSatyam/StudentDetails<file_sep>/StudentApp/src/Marks/GetMarks.ts
export class GetMarks
{
mark:string[]
activate(marks)
{
this.mark=marks;
}
}<file_sep>/StudentApp/src/Login/Login.ts
import {Router} from 'aurelia-router'
import {inject} from 'aurelia-framework';
import {ValidationRules, ValidationController} from "aurelia-validation";
@inject(ValidationController,Router)
export class App {
msg = '';
firstname: string = '';
email: string = '';
// val:boolean
router:Router
constructor(private controller: ValidationController,router:Router) {
this.router=router;
ValidationRules
.ensure((m: App) => m.email).email().required()
.ensure((m: App) => m.firstname).displayName("First name").required()
.on(this);
}
validateMe() {
this.controller
.validate().then(result=>{if(result.valid)
{
// this.msg="All is good"
this.router.navigateToRoute('Marks')
}
// this.val=true;
else
{
this.msg="you have errors"
}
// .then(v => {
// if (v.length === 0)
// this.message = "All is good!";
// else
// this.message = "You have errors!";
})
}
}<file_sep>/StudentApp/src/Region/North.ts
export class North
{
n:string []
constructor()
{
this.n=['Delhi','Jammu','Patna']
}
}
<file_sep>/StudentApp/src/Marks/Marks.ts
export class marks
{
data
subject:string
Score:number
constructor()
{
this.data=[{subject:'physic',Score:30},
{subject:'bio',Score:40},
{subject:'chem',Score:50}]
}}
<file_sep>/StudentApp/src/ContactUs/blankview.ts
export class noselection
{
}<file_sep>/StudentApp/src/Region/Region.ts
import {Router,RouterConfiguration} from 'aurelia-router'
export class App
{
router:Router;
configureRouter(config:RouterConfiguration,router:Router)
{
this.router=router;
config.title="Hell"
config.map([
{route:['','North'] ,moduleId:'Region/North',title:'RegionsInNorth',nav:true},
{route:'South',moduleId:'Region/South',nav:true,title:'RegionsInSouth'}])
}
}<file_sep>/StudentApp/src/app.ts
import {Router,RouterConfiguration} from 'aurelia-router'
export class App
{
router:Router;
configureRouter(config:RouterConfiguration,router:Router)
{
this.router=router;
config.title="Hello"
config.map([
{route:['','Login'] , moduleId:'Login/Login',title:'Login',nav:true},
{route:'Region',moduleId:'Region/Region',nav:true,title:'Region'},
{route:'ContactUs',moduleId:'ContactUs/contact', nav:true,title:'ContactUs'},
{route:'Marks',moduleId:'Marks/Marks',title:'Marks',name:"Marks"}
// {route:'contacts/:id',moduleId:'ContactUs/contact-detail',name:'contacts'}
])
config.fallbackRoute("Marks")
}
}<file_sep>/StudentApp/src/Region/South.ts
export class South
{
} | b1c3f9d3a241a5060e4a3a7c802d2fa521c5cf16 | [
"TypeScript"
] | 8 | TypeScript | SaiSatyam/StudentDetails | 6c5196874a0d8bd063b202b9ada52d4baa981688 | 0e6f8710276022172310dfcdc5779bae582dfda6 |
refs/heads/master | <file_sep>angular.module('sportsApp')
.controller('NflIndexController', ['$scope','Nfl', function($scope, Nfl){
Nfl.all()
.success(function(response){
$scope.nflTeam = response.nfl;
});
}]);
<file_sep>'use strict';
// Declare app level module which depends on views, and components
var app = angular.module('nba-teams');
app.controller('NbaCtrl', ['$scope', '$http', function($scope, $http){
//$scope.isNavCollapsed = true;
$http.get('data/nba-team-info.json')
.success(function(response){
$scope.nbaTeam = response.nba;
});
}]);
<file_sep>angular.module("sportsApp")
.directive("nwCard", function() {
var num =1;
return {
restrict: "E",
templateUrl: "partials/directives/nw-card.html",
scope: {
header: "=",
image: "=",
body: "="
},
/*controller: function($scope){
$scope.header = "Note Title" + num++;
},
controllerAs: "card"*/
};
});
<file_sep># Sports Fun
### Install Dependencies
We have two kinds of dependencies in this project: tools and angular framework code. The tools help
us manage and test the application.
* We get the tools we depend upon via `npm`, the [node package manager][npm].
* We get the angular code via `bower`, a [client-side code package manager][bower].
We have preconfigured `npm` to automatically run `bower` so we can simply do:
```
npm install
```
Behind the scenes this will also call `bower install`. You should find that you have two new
folders in your project.
* `node_modules` - contains the npm packages for the tools we need
* `app/bower_components` - contains the angular framework files
*Note that the `bower_components` folder would normally be installed in the root folder but
angular-seed changes this location through the `.bowerrc` file. Putting it in the app folder makes
it easier to serve the files by a webserver.*
### Run the Application
We have preconfigured the project with a simple development web server. The simplest way to start
this server is:
```
npm start
```
Now browse to the app at `http://localhost:8000/index.html`.
## Updating Angular
Previously we recommended that you merge in changes to angular-seed into your own fork of the project.
Now that the angular framework library code and tools are acquired through package managers (npm and
bower) you can use these tools instead to update the dependencies.
You can update the tool dependencies by running:
```
npm update
```
This will find the latest versions that match the version ranges specified in the `package.json` file.
You can update the Angular dependencies by running:
```
bower update
```
This will find the latest versions that match the version ranges specified in the `bower.json` file.
## Contact
For more information on AngularJS please check out http://angularjs.org/
[bower]: http://bower.io
[git]: http://git-scm.com/
[http-server]: https://github.com/nodeapps/http-server
[jasmine]: https://jasmine.github.io
[jdk]: https://en.wikipedia.org/wiki/Java_Development_Kit
[jdk-download]: http://www.oracle.com/technetwork/java/javase/downloads/index.html
[karma]: https://karma-runner.github.io
[node]: https://nodejs.org
[npm]: https://www.npmjs.org/
[protractor]: https://github.com/angular/protractor
[selenium]: http://docs.seleniumhq.org/
[travis]: https://travis-ci.org/
<file_sep>'use strict';
// Declare app level module which depends on views, and components
angular.module('sportsApp', ['ui.router', 'ngAnimate' ,'ngTouch'])
.config(function (GravatarProvider) {
GravatarProvider.setSize(100);
});
/*.controller('NflCtrl', ['$scope', '$http', function($scope, $http){
$scope.nflTeam = [ ];
$http.get('data/nfl-team-info.json').success(function(data){
$scope.nflTeam = data.nfl;
});
}]);*/
<file_sep>angular.module('sportsApp')
.factory("Nfl", function NflFactory($http){
return {
all: function(){
return $http({method: "GET", url: "data/nfl-team-info.json"});
}
}
});
//
| abcfcf3f8ca15e83334773cbee973484d44f8653 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | fbs70/sports-fun | a93f5f8a5aa10dac0d66f1dc721455f8271d2658 | 101811763323c2d5d4255515ac957c8cc97a83c4 |
refs/heads/master | <file_sep>\name{applyttestPep}
\alias{applyttestPep}
\title{
Function to apply t-test separately for all peptides of each protein
}
\description{
Generate fold changes and p-values for each protein (col 1) determined by a number of peptides (col 2).
}
\usage{
applyttestPep(peptides, Group, doLogs = TRUE, numerator = levels(as.factor(Group))[1])
}
\arguments{
\item{peptides}{
Data frame with two descriptive columns: proteins, peptides, then data in the remaining ncol - 2 columns.
}
\item{Group}{
Factor describing data membership. Must have two levels, and length = ncol(mat) - 2.
}
\item{doLogs}{
TRUE/FALSE, log-transform data prior to analysis
}
\item{numerator}{
The group level used as the numerator in the fold change.
}
}
\details{
}
\value{
Data frame with rows Protein, fold change and p-value.
}
\references{
}
\author{
}
\note{
}
\seealso{
\code{\link{applyttest}}
}
\examples{
# make random matrix with first 10 proteins differentially expressed
mat = exp(6+matrix(rnorm(6000), ncol=6))
Protein = sort(paste("P", sample(1:300, 1000, replace=TRUE)))
Peptide = paste("Pep", 1:1000)
for (j in 1:10) mat[Protein == unique(Protein)[j], 4:6] = 3*mat[Protein == unique(Protein)[j], 1:3]
res = applyttestPep(data.frame(Protein, Peptide, mat), rep(c("A", "B"), each=3), numerator="B")
# first 10 proteins should have fold change 3
plot(log(res$FC), -log(res$pval), col=rainbow(2)[1+ as.numeric(1:1000 > 10)])
# add some missing values
mat[5:20,4] = NA
res = applyttestPep(data.frame(Protein, Peptide, mat), rep(c("A", "B"), each=3), numerator="B")
# first 10 proteins should have fold change 3
plot(log(res$FC), -log(res$pval), col=rainbow(2)[1+ as.numeric(1:1000 > 10)])
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>\name{plotDensities}
\alias{plotDensities}
\title{
Utility to do side by side density plots
}
\description{
Side by side density plots
}
\usage{
plotDensities(data, group = rownames(data), xlab = "Log Abundance")
}
\arguments{
\item{data}{
Data with samples as columns.
}
\item{group}{
Group of the same length as the number of columns of data
}
\item{xlab}{
Label to be printed
}
}
\details{
}
\value{
No value returned, plotting only
}
\references{
}
\author{
}
\note{
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\seealso{
}
\examples{
plotDensities(iris[,-5], rep(c("A", "B"), each=2))
}
<file_sep>###########################################################################
#' Convert a data frame into OpenSWATH library format
#' @param dat a data frame of a canonical spectrum library
#' @return a data frame of a spectrum library in OpenSWATH format
#' @examples
#' libfile <- paste(system.file("files",package="SwathXtend"),"Lib2.txt",sep="/")
#' datlib <- readLibFile(libfile)
#' dat<-openSwathFormat(datlib)
############################################################################
openSwathFormat <- function(dat){
openswath.colnames <- c("PrecursorMz","ProductMz","Tr_recalibrated","transition_name","CE",
"LibraryIntensity","transition_group_id","decoy","PeptideSequence",
"ProteinName","Annotation","FullUniModPeptideName","PrecursorCharge",
"GroupLabel","UniprotID","FragmentType","FragmentCharge","FragmentSeriesNumber")
dat.res <- data.frame("PrecursorMz" = dat$Q1,
"ProductMz" = dat$Q3,
"Tr_recalibrated" = dat$RT_detected,
"transition_name" = dat$stripped_sequence,
"CE" = -1,
"LibraryIntensity" = dat$relative_intensity,
"transition_group_id" = dat$stripped_sequence,
"decoy" = dat$decoy,
"PeptideSequence" = dat$stripped_sequence,
"ProteinName" = dat$uniprot_id,
"Annotation" = paste(dat$frg_type,dat$frg_nr,sep=""),
"FullUniModPeptideName" = dat$modification_sequence,
"PrecursorCharge" = dat$prec_z,
"GroupLabel" = "light",
"UniprotID" = dat$uniprot_id,
"FragmentType" = dat$frg_type,
"FragmentCharge" = dat$frg_z,
"FragmentSeriesNumber" = dat$frg_nr)
dat.res
}<file_sep>###########################################################################
#' Plot for retention time correlation of two libraries
#' @param dat1 A data frame containing the first spectrum library
#' @param dat2 A data frame containing the second spectrum library
#' @param method a character string indicating the method for calculating
#' correlation coefficient. One of "time" (default) and "hydro".
#' @param wb an openxlsx workbook object
#' @param sheet A name or index of a worksheet
#' @param label1 a character string representing the x axis label for plotting
#' @param label2 a character string representing the y axis label for plotting
#' @param nomod a logic value, representing if the modified peptides and its
#' fragment ions will be removed. FALSE (default) means not removing.
#' @return two .png files of RT correlation and RT residual plots will be saved
#' under current working directory
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' computeRTCor(datBaseLib, datExtLib)
############################################################################
computeRTCor <- function(dat1, dat2, datHydroIndex, method=c("time", "hydro"), wb=NULL, sheet=NULL,
label1="Base Lib", label2 = "External Lib", nomod=FALSE)
{
method <- match.arg(method)
if(method == "time"){
datRTrain <- getRTrain(dat1, dat2, nomod=nomod)
bestModel <- selectModel(datRTrain)
if(nrow(datRTrain) > 10){
r2 <- cor(datRTrain[,2],datRTrain[,3])^2
predicted <- predict(bestModel, newdata=datRTrain)
rmse <- sqrt(mean((datRTrain[,2]-predicted)^2))
# plot RT correlation
png("RT_correlation.png")
plot(datRTrain[,2],datRTrain[,3],
xlab=paste(label1, "RT"),ylab=paste(label2, "RT"))
lines(lowess(datRTrain[,2],datRTrain[,3]),col="red")
r2label <- bquote(italic(R)^2 ==. (format(r2, digits = 2)))
text(min(datRTrain[,2])+2, max(datRTrain[,3])-2,
labels = r2label,pos=4)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "RT_correlation.png", width=6, height=5, startRow=1, startCol=1)
# plot residuals
png("RT_residual.png")
# plot(residuals(fit))
resids <- predicted-datRTrain[,2]
plot(resids, main=paste("Residual plot for",
attr(bestModel,"class")[length(attr(bestModel,"class"))]))
abline(h=floor(rmse),col="red")
abline(h=-floor(rmse), col="red")
axis(2, c(-floor(rmse),floor(rmse)), col.ticks="red")
rmselabel <- bquote(italic(rmse) ==. (format(rmse, digits=2)))
text(2, max(resids), labels = rmselabel, pos=4)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "RT_residual.png", width=6, height=5, startRow=1, startCol=10)
}
list(RT.cor = r2, RMSE = rmse)
} else if (method == "hydro"){
if(missing(datHydroIndex)) stop("Missing data frame of hydrophibicity index.")
colnames(datHydroIndex)[grep("sequence",tolower(colnames(datHydroIndex)))]<-
"sequence"
colnames(datHydroIndex)[grep("hydro",tolower(colnames(datHydroIndex)))] <- "hydro"
colnames(datHydroIndex)[grep("len",tolower(colnames(datHydroIndex)))] <- "length"
dat1 <- dat1[!duplicated(dat1$stripped_sequence),]
datHydroIndex <- datHydroIndex[!duplicated(datHydroIndex$sequence),]
datHydroIndex$hydro <- as.numeric(datHydroIndex$hydro)
datRTrain <- merge(dat1[,c("stripped_sequence","RT_detected")],
datHydroIndex[,c("sequence","hydro","length")],
by.x="stripped_sequence",
by.y=tolower("sequence"),all=FALSE)
datRTrain$length <- log(datRTrain$length)
f.h= as.formula("RT_detected~hydro")
f.hl <- as.formula("RT_detected~hydro+length")
if(nrow(datRTrain) > 10){
fit.h <- lm(f.h, data=datRTrain)
fit.hl <- lm(f.hl, data=datRTrain)
png("RT_correlation_hydro.png")
plot(datRTrain[,2]~datRTrain[,3],
xlab="Hydrophibicity index",ylab=paste(label1,"RT"))
r2 <- cor(datRTrain[,3],datRTrain[,2])^2
lines(lowess(datRTrain[,3],datRTrain[,2]),col="red")
r2label <- bquote(italic(R)^2 ==. (format(r2, digits = 2)))
text(min(datRTrain[,3])+2, max(datRTrain[,2])-2,
labels = r2label,pos=4)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "RT_correlation_hydro.png", width=6, height=5, startRow=1, startCol=1)
png("RT_correlation_hydroNlength.png")
layout(matrix(1:2,nrow=2))
plot(datRTrain[,2]~datRTrain[,3],
xlab=paste(label1,"Hydro"),ylab=paste(label1,"RT"))
r2 <- cor(datRTrain[,3],datRTrain[,2])^2
lines(lowess(datRTrain[,3],datRTrain[,2]),col="red")
r2label <- bquote(italic(R)^2 ==. (format(r2, digits = 2)))
text(min(datRTrain[,3])+2, max(datRTrain[,2])-2,
labels = r2label,pos=4)
plot(datRTrain[,2]~datRTrain[,4],
xlab="ln(Length)",ylab="RT",
main="Correlation between ln(Length) and RT")
r2 <- cor(datRTrain[,4],datRTrain[,2])^2
lines(lowess(datRTrain[,4],datRTrain[,2]),col="red")
r2label <- bquote(italic(R)^2 ==. (format(r2, digits = 2)))
text(max(datRTrain[,4])-0.1, min(datRTrain[,2]+10),
labels = r2label)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "RT_correlation_hydroNlength.png", width=6, height=5, startRow=1, startCol=10)
rmse.h <- sqrt(mean(resid(fit.h)^2))
rmse.hl <- sqrt(mean(resid(fit.hl)^2))
## plot
png("RT_residual_hydro.png")
plot(residuals(fit.h))
abline(h=floor(rmse.h),col="red")
abline(h=-floor(rmse.h), col="red")
axis(2, c(-floor(rmse.h),floor(rmse.h)), col.ticks="red")
rmselabel <- bquote(italic(rmse) ==. (format(rmse.h, digits=2)))
text(2, max(resid(fit.h)), labels = rmselabel, pos=4)
dev.off()
png("RT_residual_hydroNlength.png")
plot(residuals(fit.hl))
abline(h=floor(rmse.hl),col="red")
abline(h=-floor(rmse.hl), col="red")
axis(2, c(-floor(rmse.hl),floor(rmse.hl)), col.ticks="red")
rmselabel <- bquote(italic(rmse) ==. (format(rmse.hl, digits=2)))
text(2, max(resid(fit.hl)), labels = rmselabel, pos=4)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "RT_residual_hydro.png", width=6, height=5, startRow=1, startCol=20)
}
} else { # sequence
d <- dat1[,c("stripped_sequence","RT_detected")]
d.aa <- do.call(rbind, lapply(d$stripped_sequence, convertAACount))
d.aa$RT_detected <- d$RT_detected
fit.seq <- lm(RT_detected ~., d.aa[,-1])
rmse <- sqrt(mean(resid(fit.seq)^2))
plot(residuals(fit.seq))
abline(h=floor(rmse),col="red")
abline(h=-floor(rmse), col="red")
axis(2, c(-floor(rmse),floor(rmse)), col.ticks="red")
rmselabel <- bquote(italic(rmse) ==. (format(rmse, digits=2)))
text(length(resid(fit.seq))-200, max(resid(fit.seq)), labels = rmselabel,pos=2)
}
}<file_sep>\name{mlrrep}
\alias{mlrrep}
\title{
Function to do mlr normalizatiopn on a matrix of replicates
}
\description{
Calculate all pairwise ratios, log-transform them, find the least variable replicate.
}
\usage{
mlrrep(mat)
}
\arguments{
\item{mat}{
Data matrix with replicates as columns
}
}
\details{
}
\value{
\item{mat.norm}{Normalized data matrix; matrix assumed positive}
\item{wdmat}{Square matrix of half peak widths for each ratio of replicates of size ncol(mat)}
\item{nfmat}{Square matrix of normalization factors for each ratio of replicates of size ncol(mat)}
\item{idx}{Index of replicate to be used as denominator yielding smallest widths}
}
\references{
}
\author{
}
\note{
}
\seealso{
\code{\link{mlr}}, \code{\link{mlrGroup}}
}
\examples{
# Example using the iris data
mlrrep(iris[,-5])
# random data
mat = exp(matrix(rnorm(1000),ncol=4))
res = mlrrep(mat)
layout(matrix(1:2, nrow=1))
boxplot(log(res$mat.norm))
boxplot(log(mat))
}
<file_sep>\name{mlrGroup}
\alias{mlrGroup}
\title{
Function to do mlr normalization for a matrix group
}
\description{
Do mlr normalization separately for each set of replicates first, then normalize the resulting matrix
}
\usage{
mlrGroup(mat, Group)
}
\arguments{
\item{mat}{
Data matrix with replicates as columns
}
\item{Group}{
Factor of length ncol(mat)
}
}
\details{
}
\value{
Resulting normalized matrix of the same size as the initial one
}
\references{
*Find reference to mlr paper*
}
\author{
}
\note{
}
\seealso{
\code{\link{mlrrep}}, \code{\link{mlr}}
}
\examples{
res = mlrGroup(iris[,-5], Group=as.factor(c("Sepal", "Sepal", "Petal", "Petal")))
layout(matrix(1:3, nrow=1))
boxplot(log(iris[,-5]), main="Log only")
boxplot(log(medianNorm(iris[,-5])), main="Median")
boxplot(log(res[[1]]), main="MLR")
}
<file_sep>applyttestPep <-
function(peptides, Group, doLogs=TRUE, numerator=levels(as.factor(Group))[1]) {
# columns: protein, peptide, values
Protein = peptides[,1]
peptides = peptides[,-c(1:2)]
Group = as.factor(as.vector(Group))
pval = rep(NA, nrow(peptides))
FC = rep(NA, nrow(peptides))
if (doLogs == TRUE) peptides = log(peptides+1);
if (!(nlevels(Group) == 2)) stop("T test needs two levels only in group.");
mn.1 = apply(peptides[,Group == numerator], 1, FUN=function(v){mean(na.omit(v))})
mn.2 = apply(peptides[,Group == setdiff(levels(Group), numerator)], 1, FUN=function(v){mean(na.omit(v))})
# calculate FC by peptide
if (doLogs) {
FC = exp(mn.1)/exp(mn.2)
} else {
FC = mn.1/mn.2
}
# calculate pval by protein from peptide ratios
ag.peptide.pval = aggregate(FC, by=list(Protein=Protein),
FUN=function(v){ res=NA;tp=try(t.test(log(v)));
if (!inherits(tp, "try-error")) res=tp$p.value; res})
# calculate FC by protein
ag.peptide.FC = aggregate(FC, by=list(Protein=Protein),
FUN=function(v){ exp(mean(log(na.omit(v))))})
if ( sum(ag.peptide.FC[,1] != ag.peptide.pval[,1]) > 0) stop("Error in calculating peptide level tests.")
res = data.frame(ag.peptide.pval, ag.peptide.FC[,-1])
colnames(res) = c("Protein", "pval", "FC")
res[match(unique(Protein), res[,1]),]
}
<file_sep>\name{medianNorm}
\alias{medianNorm}
\title{
Utility to median normalize a matrix by columns
}
\description{
Divide appropriately to make all column medians equal to the max median
}
\usage{
medianNorm(mat)
}
\arguments{
\item{mat}{
Data matrix to normalize; matrix assumed positive
}
}
\details{
}
\value{
Matrix of same dimensions.
}
\references{
}
\author{
}
\note{
}
\seealso{
}
\examples{
mat = 100+matrix(rnorm(1000), ncol=10)
mat[,10] = mat[,10] + 2
layout(matrix(1:2, nrow=1))
boxplot(mat)
boxplot(medianNorm(mat))
# note: issues when medians close to 0.
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>###########################################################################
#' Standardise a data frame into library format
#' @param datlib a data frame for a spectrum library
#' @param colnums a number representing the number of columns to keep
#' (default as 18)
#' @return a data frame with specified number of columns
#' @examples
#' libfile <- paste(system.file("files",package="SwathXtend"),"Lib2.txt",sep="/")
#' datlib <- readLibFile(libfile)
#' dat <- libraryFormat(datlib)
############################################################################
libraryFormat <- function(datlib, colnums = 18)
{
inclcols = c("Q1","Q3",
"RT_detected",
"protein_name",
"isotype",
"relative_intensity",
"stripped_sequence",
"modification_sequence",
"prec_z",
"frg_type",
"frg_z",
"frg_nr",
"iRT",
"uniprot_id",
"decoy",
"confidence",
"shared",
"N")
datlib[,inclcols]
}<file_sep>applyttest <-
function(mat, Group, doLogs=TRUE, numerator=levels(Group)[1]) {
Group = as.factor(as.vector(Group))
mat = as.matrix(mat)
pval = rep(NA, nrow(mat))
FC = rep(NA, nrow(mat))
if (doLogs == TRUE) mat = log(mat);
if (!(nlevels(Group) == 2)) stop("T test needs two levels only in group.");
pval = sapply(1:nrow(mat), FUN=function(i){
res = NA
tp = try(t.test(mat[i,] ~ Group, var.equal=TRUE))
if (!inherits(tp, "try-error")) res = tp$p.value
res
})
mn.1 = apply(mat[,Group == numerator], 1, FUN=function(v){mean(na.omit(v))})
mn.2 = apply(mat[,Group == setdiff(levels(Group), numerator)], 1, FUN=function(v){mean(na.omit(v))})
if (doLogs) {
FC = exp(mn.1)/exp(mn.2)
} else {
FC = mn.1/mn.2
}
data.frame(pval, FC)
}
<file_sep>\name{applyttest}
\alias{applyttest}
\title{
Utility to apply a t-test to all rows of a matrix
}
\description{
Generate fold change and t-test p-value for all rows of a data matrix
}
\usage{
applyttest(mat, Group, doLogs = TRUE, numerator = levels(Group)[1])
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{mat}{
Matrix containing data, possibly with missing values
}
\item{Group}{
Group with two levels of length equal to the number of matrix columns
}
\item{doLogs}{
True/false, log data before applying test
}
\item{numerator}{
The level of the group used as numerator for the fold change, by default the first one
}
}
\details{
}
\value{
Data frame with two values, t-test p-value and fold change.
}
\references{
}
\author{
}
\note{
}
\seealso{
\code{\link{applyttestPep}}
}
\examples{
mat = matrix(rnorm(600), nrow=100)
mat[1:20, 1:3] = 3+mat[1:20, 1:3] # create some differences
mat[30, 1:3] = NA # and some missing values
mat[100,] = NA
applyttest(mat, Group = rep(c("A", "B"), each=3), doLogs=FALSE)
applyttest(abs(mat), Group = rep(c("A", "B"), each=3), doLogs=TRUE)
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>\name{plotAll}
\alias{plotAll}
\title{Plot statistical plots for two libraries}
\usage{
plotAll(datBaseLib, datExtLib, file = "allplots.xlsx", ...)
}
\arguments{
\item{datBaseLib}{a data frame for a base spectrum library}
\item{datExtLib}{a data frame for a external spectrum library}
\item{file}{a character string for the output file}
\item{\dots}{
Additional parameters to pass in
}
}
\description{
Plot statistical plots for two libraries
}
\value{
a list of two data frames
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
datBaseLib <- readLibFile(libfiles[1])
datExtLib <- readLibFile(libfiles[2])
res <- plotAll(datBaseLib, datExtLib)
}
<file_sep>###########################################################################
#' Plot the statistical summary of the base and external libraries
#' @param datBaseLib a data frame for base library
#' @param datExtLib a data frame for external/addon library
#' @param wb an openxlsx workbook object
#' @param sheet A name or index of a worksheet
#' @param ... arguments to pass onto cleanLib function
#' @return .png files of statistical plots of the two libraries
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' plotStats(datBaseLib, datExtLib)
############################################################################
plotStats <- function(datBaseLib, datExtLib, wb=NULL, sheet=NULL, ...)
{
if(!missing(datExtLib)){ ## 2 libs
## protein peptide numbers
nums.pro <- sapply(list(datBaseLib$uniprot_id,datExtLib$uniprot_id),
FUN=function(x){length(unique(x))})
names(nums.pro) <- c("Base", "Addon")
nums.pep <- sapply(list(datBaseLib$stripped_sequence,datExtLib$stripped_sequence),
FUN=function(x){length(unique(x))})
names(nums.pep) <- c("Base", "Addon")
png("protein_peptide_numbers.png")
layout(matrix(1:2,nrow=1))
barplot(nums.pro, col=c("darkblue","red"),beside=TRUE,main="Proteins")
barplot(nums.pep, col=c("darkblue","red"),beside=TRUE,main="Peptides")
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "protein_peptide_numbers.png", width=6, height=5, startRow=1, startCol=1)
## Venn diagrams
#grid.newpage()
if(nums.pro[1]>0 && nums.pro[2]>0){
png("proteinVennDigram.png")
draw.pairwise.venn(nums.pro[1], nums.pro[2],
length(proteinOverlap(datBaseLib,datExtLib, ...)),
category = c("Base Library Proteins", "External Library Proteins"),
lty = rep("blank", 2),
fill = c("light blue", "pink"),
alpha = rep(0.5, 2), cat.pos = c(0,20),
cat.dist = rep(0.025, 2))
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "proteinVennDigram.png", width=5, height=5, startRow=1, startCol=15)
}
if(nums.pep[1]>0 && nums.pep[2]>0){
png("peptideVennDigram.png")
draw.pairwise.venn(nums.pep[1], nums.pep[2],
length(unique(intersect(datBaseLib$stripped_sequence,
datExtLib$stripped_sequence))),
category = c("Base Library Peptides", "External Library Peptides"),
lty = rep("blank", 2),
fill = c("light blue", "pink"),
alpha = rep(0.5, 2), cat.pos = c(0,20),
cat.dist = rep(0.025, 2))
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "peptideVennDigram.png", width=5, height=5, startRow=1, startCol=25)
}
# Density plots
png("densityPlots.png")
layout(matrix(1:4,ncol=2))
plot(density(datBaseLib$confidence), main="Base lib conf", xlab="Confidence")
abline(v=0.99,col="red")
plot(density(datExtLib$confidence), main="Addon lib conf", xlab="Confidence")
abline(v=0.99, col="red")
plot(density(log(datBaseLib$relative_intensity)), main="Base lib ion intensity", xlab="log ion intensity")
abline(v=1.6, col="red") #log5
plot(density(log(datExtLib$relative_intensity)), main="Addon lib ion intensity", xlab="log ion intensity")
abline(v=1.6, col="red")
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "densityPlots.png", width=6, height=6, startRow=30, startCol=1)
# histgrams of peptides/protein and ions/peptide
png("histgram_peptide_ion.png")
layout(matrix(1:4,ncol=2))
x<-aggregate(datBaseLib$uniprot_id, by=list(Protein=datBaseLib$uniprot_id, Peptide=datBaseLib$stripped_sequence),
FUN=function(x){length(x)})
y<-aggregate(x$Peptide, by=list(Protein=x$Protein), FUN=function(x){length(x)})
hist(x[,3], xlab="Number of ions per peptide", main="Base lib")
hist(y[,2], breaks="Sturges",xlab="Number of peptides per protein", main="Base lib")
x<-aggregate(datExtLib$uniprot_id, by=list(Protein=datExtLib$uniprot_id, Peptide=datExtLib$stripped_sequence),
FUN=function(x){length(x)})
y<-aggregate(x$Peptide, by=list(Protein=x$Protein), FUN=function(x){length(x)})
hist(x[,3], xlab="Number of ions per peptide", main="Addon lib")
hist(y[,2], breaks=5, xlab="Number of peptides per protein", main="Addon lib", freq=FALSE)
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "histgram_peptide_ion.png", width=6, height=6, startRow=30, startCol=15)
} else { # single lib
nums.pro <- length(unique(datBaseLib$uniprot_id))
nums.pep <- length(unique(datBaseLib$stripped_sequence))
png("protein_peptide_numbers.png")
par(mfrow=c(1,2))
barplot(nums.pro,col="lightblue",main="Proteins",ylim = c(0,max(nums.pro)))
barplot(nums.pep,col="lightseagreen",main="Peptides",ylim = c(0,max(nums.pep)))
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "protein_peptide_numbers.png", width=6, height=5, startRow=1, startCol=1)
png("densityPlots.png")
layout(matrix(1:2,ncol=2))
plot(density(datBaseLib$confidence), main="Base lib conf", xlab="Confidence")
abline(v=0.99,col="red")
plot(density(log(datBaseLib$relative_intensity)), main="Ion intensity", xlab="log ion intensity")
abline(v=1.6, col="red") #log5
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "densityPlots.png", width=6, height=6, startRow=30, startCol=1)
}
}
<file_sep>mlrrep <-
function(mat) {
n = ncol(mat)
nfmat = matrix(0, n, n)
wdmat = matrix(0, n, n)
res.list = list()
# calculate all mlr's
for (i in 2:n) {
for (j in (1:(i-1)) ) {
tp = mlr(na.omit(log(mat[,i]/mat[,j])))
res.list[[paste(i,j)]] = tp
nfmat[i,j] = tp$nf
wdmat[i,j] = tp$wdt
}
}
wdmat[upper.tri(wdmat)] = t(wdmat)[upper.tri(t(wdmat))]
nfmat[upper.tri(nfmat)] = -t(nfmat)[upper.tri(t(nfmat))]
# find least variable replicate
idx = which.min(apply(wdmat, 1, FUN=sum))
mat.norm = mat
for ( j in setdiff(1:n, idx) ) mat.norm[,j] = exp(nfmat[idx,j])*mat[,j];
list(mat.norm=mat.norm, wdmat=wdmat, nfmat=nfmat, idx=idx)
}
<file_sep>\name{ionCorGS}
\docType{data}
\alias{ionCorGS}
\title{Gold standard relative ion intensity correlation (spearman)}
\description{
This data set gives the relative ion intensity spearman correlation for 2023 peptides as the gold standard
for benchmarking the matching quality of two peptide assay libraries.
}
\usage{data(ionCorGS)}
\format{A vector containing spearman correlation coefficient for 2023 peptides.}
\value{a numeric vector}
\source{APAF}
\references{
APAF
}
\keyword{datasets}<file_sep>plotDensities <- function (data, group = rownames(data), xlab = "Log Abundance")
{
group <- as.factor(group)
colours <- rainbow(length(levels(group)))
col <- colours[group]
# par(mfrow = c(1, 1))
x <- t(as.matrix(data))
ndx <- rep(FALSE, ncol(x))
for (i in 1:ncol(x)) ndx[i] <- is.numeric(x[, i])
if (sum(ndx) > 0) {
x <- x[, ndx, drop = FALSE]
try(d1 <- density(as.vector(as.matrix(x))))
if (inherits(d1, "try-error"))
warning("Failed to generate the density plots")
ymx <- max(d1$y)
plot(d1, type = "n", xlab = xlab, ylab = "Density", main = "Sample Densities",
ylim = c(0, 2 * ymx), yaxp = c(0, 2 * ymx, 5))
for (i in 1:ncol(x)) {
try(d1 <- density(x[, i]))
if (inherits(d1, "try-error"))
warning(paste("Failed to generate the density plot for sample",
i))
lines(d1, lty = i, col = col[i])
}
legend("topright", legend = levels(group), col = colours,
lty = 1)
}
}
<file_sep>\name{plotRelativeDensities}
\alias{plotRelativeDensities}
\title{
Plotting utility to overlay all relative densities
}
\description{
Overlay all relative densities
}
\usage{
plotRelativeDensities(mat, Group = NULL, idx = NULL, main = "Densities")
}
\arguments{
\item{mat}{
Matrix with positive entries, samples as columns
}
\item{Group}{
The factor showing the sample membership, of length ncol(mat)
}
\item{idx}{
Number between 1:ncol(mat); which sample to use as denominator, first one by default
}
\item{main}{
Title; optional
}
}
\details{
}
\value{
Plotting only
}
\references{
}
\author{
}
\note{
}
\seealso{
}
\examples{
mat = matrix(abs(rnorm(50000)), ncol=5)
mat[,5] = mat[,5] + 2
plotRelativeDensities(mat, Group=c(rep("A",4),"B"), idx=1)
}
<file_sep>
###############################################################################
#' Checking for the integration quality of two libraries
#' @param datBaseLib a data frame of the base library
#' @param datExtLib a data frame of the add-on library
#' @return A list of quality indicators, including squared retention time (RT)
#' correlation coefficient, root mean squared errors of RT residuals,
#' and median of relative ion intensity correlation coefficient
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' res <- checkQuality(datBaseLib, datExtLib)
###############################################################################
checkQuality <- function(datBaseLib, datExtLib, ...)
{
list.datLibs <- try(splitLib(datBaseLib, datExtLib))
if(inherits(list.datLibs,"try-error"))
stop("Error with splitting datExtLib")
datExtLibCommPart <- list.datLibs[["ExtCommon"]]
datBaseCommPart <- list.datLibs[["BaseCommon"]]
rtcorsqr <- try(computeRTCor(datBaseCommPart,datExtLibCommPart, ...))
if(inherits(rtcorsqr,"try-error"))
stop("Error with computeRTCor")
ioncors<- try(computeRIICor(datBaseCommPart,datExtLibCommPart, ...))
if(inherits(ioncors,"try-error"))
stop("Error with computeRIICor")
ioncormedian <- median(ioncors)
list(RT.corsqr=rtcorsqr$RT.cor , RT.RMSE=rtcorsqr$RMSE, RII.cormedian= ioncormedian)
}<file_sep>###########################################################################
#' Plot residuals for retention time prediction of two libraries
#' @param dat1 A data frame containing the first spectrum library
#' @param dat2 A data frame containing the second spectrum library
#' @param nomod a logic value, representing if the modified peptides and its
#' fragment ions will be removed. FALSE (default) means not removing.
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' plotRTResd(datBaseLib, datExtLib)
############################################################################
plotRTResd <- function(dat1, dat2, nomod=FALSE) {
datRTrain <- getRTrain(dat1, dat2, nomod=nomod)
bestModel <- selectModel(datRTrain)
predicted <- predict(bestModel, newdata=datRTrain)
rmse <- sqrt(mean((datRTrain[,2]-predicted)^2))
resids <- predicted-datRTrain[,2]
plot(resids, main=paste("Residual plot for",
attr(bestModel,"class")[length(attr(bestModel,"class"))]))
abline(h=floor(rmse),col="red")
abline(h=-floor(rmse), col="red")
axis(2, c(-floor(rmse),floor(rmse)), col.ticks="red")
rmselabel <- bquote(italic(rmse) ==. (format(rmse, digits=2)))
text(2, max(resids), labels = rmselabel, pos=4)
invisible(rmse)
}<file_sep>
###########################################################################
#' Plot statistical plots for two libraries
#' @param datBaseLib a data frame for a base spectrum library
#' @param datExtLib a data frame for a external spectrum library
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' plotAll(datBaseLib, datExtLib)
############################################################################
plotAll <- function(datBaseLib, datExtLib, file="allplots.xlsx", ...)
{
wb <- createWorkbook()
# plot stats
addWorksheet(wb, sheetName="Library stats")
pstats <- try(plotStats(datBaseLib, datExtLib, wb=wb, sheet="Library stats", ...))
if(inherits(pstats, "try-error"))
stop("Error with plotStats")
list.datLibs <- try(splitLib(datBaseLib, datExtLib))
if(inherits(list.datLibs,"try-error"))
stop("Error with splitting datExtLib")
datExtLibCommPart <- list.datLibs[["ExtCommon"]]
datBaseCommPart <- list.datLibs[["BaseCommon"]]
# plot RT correlation
addWorksheet(wb, sheetName="RT cor")
rtcor <- try(computeRTCor(datBaseCommPart,datExtLibCommPart, wb=wb, sheet="RT cor"))
if(inherits(rtcor,"try-error"))
stop("Error with computeRTCor")
# plot RII correlation
addWorksheet(wb, sheetName="Relative Ion Intensity cor")
ioncor<- try(computeRIICor(datBaseCommPart,datExtLibCommPart, wb=wb, sheet="Relative Ion Intensity cor"))
if(inherits(ioncor,"try-error"))
stop("Error with computeRIICor")
saveWorkbook(wb, file=file, overwrite=TRUE)
invisible(list(rtcor = rtcor, ioncor=ioncor) )
}<file_sep>
\name{plotRIICor}
\alias{plotRIICor}
\title{Plot relative ion intensity correlation of two libraries}
\usage{
plotRIICor(dat1, dat2, nomod = FALSE)
}
\arguments{
\item{dat1}{A data frame containing the first spectrum library}
\item{dat2}{A data frame containing the second spectrum library}
\item{nomod}{a logic value, representing if the modified peptides and its
fragment ions will be removed. FALSE (default) means not removing.}
}
\description{
Plot relative ion intensity correlation of two libraries
}
\value{
a data frame of relative ion intensity correlations for all ions
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
datBaseLib <- readLibFile(libfiles[1])
datExtLib <- readLibFile(libfiles[2])
plotRIICor(datBaseLib, datExtLib)
}
<file_sep>\name{cleanLib}
\alias{cleanLib}
\title{Spectrum library cleanining}
\usage{
cleanLib(datLib, clean = TRUE, intensity.cutoff = 5, conf.cutoff = 0.99,
nomod = TRUE, nomc = FALSE, enz = c("trypsin", "gluc", "chymotrypsin"))
}
\arguments{
\item{datLib}{a data frame for a spectrum library}
\item{clean}{a logic value indicating if the library will be cleaned. Default value is TRUE.}
\item{intensity.cutoff}{A number value to specify cut off for relative
intensity of fragment ions. Only ions with intensity higher than the
cut off value (default as 5) will be kept.}
\item{conf.cutoff}{A number value to specify cut off for precursor
confidence. Only ions with confidence higher than the cut off value
(default as 0.99) will be kept.}
\item{nomod}{a logic value, representing if the modified peptides and its
fragment ions will be removed. True (default) means will be removed.}
\item{nomc}{a logic value, representing if peptides with miss cleavages
are removed. Default vaue is False (not to remove).}
\item{enz}{A character string representing the enzyme which can be one of
"trypsin" (defalut), "gluc", or "chymotrypsin"}
}
\value{
a data frame of a cleaned spectrum library by the specified
criteria
}
\description{
Spectrum library cleanining
}
\examples{
file <- paste(system.file("files",package="SwathXtend"),"Lib1.txt",sep="/")
dat <- read.delim2(file,sep="\\t",header=TRUE,stringsAsFactors=FALSE)
dat <- canonicalFormat(dat)
dat <- cleanLib(dat)
}
<file_sep>###########################################################################
#' Plot for retention time correlation of two libraries
#' @param dat1 A data frame containing the first spectrum library
#' @param dat2 A data frame containing the second spectrum library
#' @param label1 a character string representing the x axis label for plotting
#' @param label2 a character string representing the y axis label for plotting
#' @param nomod a logic value, representing if the modified peptides and its
#' fragment ions will be removed. FALSE (default) means not removing.
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' plotRTCor(datBaseLib, datExtLib, "Lib2", "Lib5")
############################################################################
plotRTCor <- function(dat1, dat2, label1, label2, nomod=FALSE) {
datRTrain <- getRTrain(dat1, dat2, nomod=nomod)
bestModel <- selectModel(datRTrain)
r2 <- cor(datRTrain[,2],datRTrain[,3])^2
predicted <- predict(bestModel, newdata=datRTrain)
rmse <- sqrt(mean((datRTrain[,2]-predicted)^2))
plot(datRTrain[,2],datRTrain[,3],
xlab=paste(label1, "RT"),ylab=paste(label2, "RT"))
lines(lowess(datRTrain[,2],datRTrain[,3]),col="red")
r2label <- bquote(italic(R)^2 ==. (format(r2, digits = 2)))
text(min(datRTrain[,2])+2, max(datRTrain[,3])-2,
labels = r2label,pos=4)
invisible(r2)
}<file_sep>###########################################################################
#' Plot for ion intensity ranking correlation of two libraries
#' @param dat1 A data frame containing the first spectrum library
#' @param dat2 A data frame containing the second spectrum library
#' @param method a character string indicating the method for calculating
#' @param wb an openxlsx workbook object
#' @param sheet A name or index of a worksheet
#' correlation coefficient. Either of "spearman" (default) or "kendall".
#' @return a .png file of boxplot for the ion intensity ranking correlation
#' between the two libraries
#' @examples
#' file1 <- paste(system.file("files",package="SwathXtend"),"Lib2.txt",sep="/")
#' file2 <- paste(system.file("files",package="SwathXtend"),"Lib3.txt",sep="/")
#' dat1 <- normalise(readLibFile(file1))
#' dat2 <- normalise(readLibFile(file2))
#' computeRIICor(dat1, dat2)
############################################################################
computeRIICor <- function(dat1,dat2, method = "spearman", wb=NULL, sheet=NULL, nomod=FALSE)
{
datRTrain <- getRTrain(dat1, dat2, nomod=nomod)
comm.peps <- unique(datRTrain$sequence)
# comm.peps <- unique(intersect(dat1$stripped_sequence,
# dat2$stripped_sequence))
cols <- c("stripped_sequence", "relative_intensity", "frg_type", "frg_nr",
"frg_z" )
if(nomod) {
datlibs.sub = lapply(list(dat1, dat2),
function(x){x[x$stripped_sequence %in%
comm.peps,cols]})
datlibs.sub = lapply(datlibs.sub,
function(x) {x$frg_type_nr=
paste(x$stripped_sequence,x$frg_type,x$frg_nr,x$frg_z)
x})
} else { # with modification
datlibs.sub = lapply(list(dat1, dat2),
function(x){
x$stripped_sequence <- paste(x$stripped_sequence,x$modification_sequence)
x[x$stripped_sequence %in% comm.peps,cols]})
datlibs.sub = lapply(datlibs.sub,
function(x) {x$frg_type_nr=
paste(x$stripped_sequence,x$frg_type,x$frg_nr,x$frg_z)
x})
}
mm = merge(datlibs.sub[[1]][,c(1,2,6)],datlibs.sub[[2]][,c(1,2,6)],by=3,all=FALSE)
if(nrow(mm) > 5){
mm = mm[!duplicated(mm$frg_type_nr),c(1,2,3,5)]
colnames(mm) <- c("frg_type_nr","stripped_sequence","relative_intensity.x",
"relative_intensity.y")
## correlation statistics
list.ms2 <- split(mm,as.factor(mm$stripped_sequence))
if(length(list.ms2) > 1){
allCor<-unlist(sapply(list.ms2, FUN=function(x)
{if(nrow(x)>1 & length(unique(x[,3]))>1 & length(unique(x[,4]))>1) {cor(x[,3],x[,4],method=method)}}) )
ionCorGS<-NULL; rm(ionCorGS);
data(ionCorGS)
png("IonIntensityCorrelation.png")
boxplot(allCor, ionCorGS, names=c("in study", "gold standard"),
col=c("darkgreen", "darkorange"),
main="Relative ion intensity correlation between libraries",outline=FALSE)
abline(h=0.8, col="red")
dev.off()
if(!is.null(wb) & !is.null(sheet))
insertImage(wb, sheet, "IonIntensityCorrelation.png", width=6, height=5, startRow=1, startCol=1)
}
}
allCor
}<file_sep>\name{canonicalFormat}
\alias{canonicalFormat}
\title{Standardise a sprectrum library data frame}
\usage{
canonicalFormat(dat, format = c("peakview", "openswath"))
}
\arguments{
\item{dat}{a data frame of a spectrum library}
\item{format}{a character string, representing the format of the input
spectrum library. One of "peakview" (default) and "openswath"
}
}
\description{
Standardise a sprectrum library data frame
}
\value{
a data frame of the library in canonical format
}
\examples{
file <- paste(system.file("files",package="SwathXtend"),"Lib1.txt",sep="/")
dat <- read.delim2(file,sep="\\t",stringsAsFactor = FALSE, header=TRUE)
dat <- try(canonicalFormat(dat, format = "peakview"))
}
<file_sep>\name{outputLib}
\alias{outputLib}
\title{output a spectrum library into a PeakView format file}
\usage{
outputLib(dat, filename = "NewLib.txt", format = c("peakview", "openswath"),
nodup = TRUE)
}
\arguments{
\item{dat}{A data frame of a spectrum library}
\item{filename}{A character string for the name of the output.}
\item{format}{A character string representing the output format. One of
"peakview" (default) and "openswath".}
\item{nodup}{A logic value, indicating if remove duplicated
sprectrum (default)}
}
\value{
a file with the specified file name (lib.txt as default) will be
saved under the current working directory
}
\description{
output a spectrum library into a PeakView format file
}
\examples{
file <- paste(system.file("files",package="SwathXtend"),"Lib1.txt",sep="/")
dat <- readLibFile(file)
outputLib(dat)
}
<file_sep>\name{plotRTResd}
\alias{plotRTResd}
\title{Plot residuals for retention time prediction of two libraries}
\usage{
plotRTResd(dat1, dat2, nomod = FALSE)
}
\arguments{
\item{dat1}{A data frame containing the first spectrum library}
\item{dat2}{A data frame containing the second spectrum library}
\item{nomod}{a logic value, representing if the modified peptides and its
fragment ions will be removed. FALSE (default) means not removing.}
}
\description{
Plot residuals for retention time prediction of two libraries
}
\value{
root mean square error of prediction residuals
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
datBaseLib <- readLibFile(libfiles[1])
datExtLib <- readLibFile(libfiles[2])
plotRTResd(datBaseLib, datExtLib)
}
<file_sep>plotErrorBarsLines <-
function (v, barSizes, lines, labels = NULL, col = "blue", ylim=c(min(lines), max(lines)),
...)
{
barSizes[is.na(barSizes)] <- 0
topBars <- v + 0.5 * barSizes
bottomBars <- v - 0.5 * barSizes
N <- length(v)
if (is.null(labels))
labels <- 1:N
ylims <- c(min(bottomBars, ylim[1], min(lines)), max(topBars,
ylim[2], max(lines)))
par(pch = 19, xaxt = "n")
plot(as.numeric(labels), v, ylim = ylims, col = col, type = "b",
lwd = 3, ...)
par(xaxt = "s")
my.at <- 1:N
axis(1, at = my.at, labels = labels)
for (i in 1:N) {
lines(c(i, i), c(topBars[i], bottomBars[i]))
}
for (i in 1:ncol(lines)) {
lines(as.numeric(labels), lines[, i], lwd = 0.5, lty = "dotted",
col = "gray")
}
}
<file_sep>mlr <-
function(ratio, doplot=FALSE) {
ratio = na.omit(ratio)
if (min(ratio) == max(ratio)) {
if (doplot) hist(ratio, freq=FALSE, breaks = 100);
out = list(nf=0, peak=1, wdt=0)
} else {
res = density(ratio)
mlr = max(res$y)
nf = res$x[which.max(res$y)]
mid = res$x[res$y > mlr/2]
wdt = mid[length(mid)] - mid[1]
out = list( nf=nf, peak=mlr, wdt=wdt)
if (doplot) {
hist(ratio, freq=FALSE, breaks = 100)
lines(res)
abline(v=0, col="red")
abline(v=nf, col="green", lwd=2)
text(nf, mlr, format(nf, digits=3), pos=4)
segments( mid[1], mlr/2, mid[length(mid)], mlr/2, col="blue", lwd=2)
text(mid[length(mid)], mlr/2, format(wdt, digits=3), col="blue", pos=4)
}
}
out
}
<file_sep>\name{mlr}
\alias{mlr}
\title{
Function to implement mlr normalization
}
\description{
Calculate normalization factor, histogram peak and width at half peak for a vector
}
\usage{
mlr(ratio, doplot)
}
\arguments{
\item{ratio}{
Vector, typically of log ratios
}
\item{doplot}{
A logic value, wheter to plot the ratio histograms (FALSE as default)
}
}
\details{
}
\value{
\item{nf}{Normalization factor}
\item{peak}{Histogram peak}
\item{wdt}{Width at half peak}
}
\references{
Find mlr reference.
}
\author{
}
\note{
}
\seealso{
}
\examples{
mlr(rnorm(1000))
# with shift
mlr(0.5 + rnorm(10000))
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>\name{plotRTCor}
\alias{plotRTCor}
\title{Plot for retention time correlation of two libraries}
\usage{
plotRTCor(dat1, dat2, label1, label2, nomod = FALSE)
}
\arguments{
\item{dat1}{A data frame containing the first spectrum library}
\item{dat2}{A data frame containing the second spectrum library}
\item{label1}{a character string representing the x axis label for plotting}
\item{label2}{a character string representing the y axis label for plotting}
\item{nomod}{a logic value, representing if the modified peptides and its
fragment ions will be removed. FALSE (default) means not removing.}
}
\description{
Plot for retention time correlation of two libraries
}
\value{
retentiont time correlation coefficient
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
datBaseLib <- readLibFile(libfiles[1])
datExtLib <- readLibFile(libfiles[2])
plotRTCor(datBaseLib, datExtLib, "Lib2", "Lib5")
}
<file_sep>
buildSpectraLibPair<-function(baseLib,extLib, hydroIndex,
method = c("time", "hydro", "hydrosequence"),
includeLength = FALSE,
labelBase = NA,
labelAddon = NA,
formatBase = c("peakview", "openswath"),
formatExt = c("peakview", "openswath"),
outputFormat = c("peakview", "openswath"),
outputFile = "extendedLibrary.txt",
plot = FALSE,
clean = TRUE,
merge = TRUE,
parseAcc = TRUE,
consolidateAccession=TRUE, ...)
{
if(!is.data.frame(baseLib)){
datBaseLib <- try(readLibFile(baseLib, format = formatBase, clean=clean, ...))
if(inherits(datBaseLib, "try-error"))
stop(paste("Error with reading", baseLib))
} else {
datBaseLib <- baseLib
}
if(!is.data.frame(extLib)){
datExtLib <- try(readLibFile(extLib, format = formatExt, clean=clean, ...))
if(inherits(datExtLib,"try-error"))
stop(paste("Error with reading", extLib))
} else {
datExtLib <- extLib
}
datBaseLib <- try(normalise(datBaseLib))
if(inherits(datBaseLib,"try-error"))
stop("Error with normalising datBaseLib")
datExtLib <- try(normalise(datExtLib))
if(inherits(datExtLib,"try-error"))
stop("Error with normalising datExtLib")
## split datExtLib into common and new
list.datLibs <- try(splitLib(datBaseLib, datExtLib,
nomod=list(...)[['nomod']]))
if(inherits(list.datLibs,"try-error"))
stop("Error with splitting datExtLib")
datExtLibCommPart <- list.datLibs[["ExtCommon"]]
datExtLibNewPart <- list.datLibs[["ExtNew"]]
datBaseCommPart <- list.datLibs[["BaseCommon"]]
if(plot)
pall<-try(plotAll(datBaseLib, datExtLib, parseAcc=parseAcc))
if(nrow(datBaseCommPart[!duplicated(datBaseCommPart$stripped_sequence),]) < 20)
{
warning("common peptides are less than 20. ")
}
method <- match.arg(method)
if(method == "time"){
datExtLibNewPart <- try(predictRT(datBaseCommPart,
datExtLibCommPart,
datExtLibNewPart,nomod=list(...)[['nomod']]))
if(inherits(datExtLibNewPart,"try-error"))
stop("Error with predictRT")
} else if (grepl("hydro",method)) {
if(!is.data.frame(hydroIndex)){
datHydroIndex <- try(readLibFile(hydroIndex, type="Hydro"))
if(inherits(datHydroIndex, "try-error"))
stop("Error with reading hydroindex file")
} else {
datHydroIndex <- hydroIndex
}
datExtLibNewPart <- try(alignRTbyHydro(datBaseLib,
datExtLibNewPart,
datHydroIndex,
method=method,
includeLength=includeLength))
if(inherits(datExtLibNewPart,"try-error"))
stop("Error with alignRTbyHydro")
} else stop(paste("Unknow method ", method))
## RE-GROUPING by common uniprot accession
datBaseCommPart <- libraryFormat(datBaseCommPart)
datBaseLib <- libraryFormat(datBaseLib)
datExtLibNewPart <- libraryFormat(datExtLibNewPart)
if(consolidateAccession)
datExtLibNewPart <-
consolidateAccession(datBaseLib, datExtLibNewPart)
## Merge base with aligned external new part
datExtLibNewPart = libraryFormat(datExtLibNewPart)
if(!is.na(labelBase)){
datBaseLib$uniprot_id <- paste(datBaseLib$uniprot_id, labelBase, sep="_")
}
if(!is.na(labelAddon)){
datExtLibNewPart$uniprot_id <- paste(datExtLibNewPart$uniprot_id, labelAddon, sep="_")
}
res <- datExtLibNewPart
if(merge) {
datlib.fin = rbind(datBaseLib,datExtLibNewPart)
datlib.fin = libraryFormat(datlib.fin)
outputLib(datlib.fin, filename=outputFile, format=outputFormat)
res <- datlib.fin
}
res
}
<file_sep>plotRelativeDensities <-
function(mat, Group=NULL, idx=NULL, main="Densities") {
n = ncol(mat)
if (is.null(Group)) Group = rep("A", ncol(mat))
Group = as.factor(Group)
if (is.null(idx)) idx = 1;
C = rainbow(nlevels(Group))[Group]
# empty plot
plot(density(log(na.omit(mat[,1]))), type="n", ylim=c(0,2), xlim=c(-5,5), main=main)
abline(v=0, col="blue")
# calculate all relative ratios
for (i in 1:n) {
if (i != idx) lines(density(log(na.omit(mat[,i]/mat[,idx]))), col=C[i]);
}
}
<file_sep>###########################################################################
#' Plot relative ion intensity correlation of two libraries
#' @param dat1 A data frame containing the first spectrum library
#' @param dat2 A data frame containing the second spectrum library
#' @param nomod a logic value, representing if the modified peptides and its
#' fragment ions will be removed. FALSE (default) means not removing.
#' @examples
#' libfiles <- paste(system.file("files",package="SwathXtend"),
#' c("Lib2.txt","Lib3.txt"),sep="/")
#' datBaseLib <- readLibFile(libfiles[1])
#' datExtLib <- readLibFile(libfiles[2])
#' plotRIICor(datBaseLib, datExtLib)
############################################################################
plotRIICor <- function(dat1, dat2, nomod=FALSE) {
datRTrain <- getRTrain(dat1, dat2, nomod=nomod)
comm.peps <- unique(datRTrain$sequence)
cols <- c("stripped_sequence", "relative_intensity", "frg_type", "frg_nr",
"frg_z" )
datlibs.sub = lapply(list(dat1, dat2),
function(x){
x$stripped_sequence <- paste(x$stripped_sequence,x$modification_sequence)
x[x$stripped_sequence %in% comm.peps,cols]})
datlibs.sub = lapply(datlibs.sub,
function(x) {x$frg_type_nr=
paste(x$stripped_sequence,x$frg_type,x$frg_nr,x$frg_z)
x})
mm = merge(datlibs.sub[[1]][,c(1,2,6)],datlibs.sub[[2]][,c(1,2,6)],by=3,all=FALSE)
mm = mm[!duplicated(mm$frg_type_nr),c(1,2,3,5)]
colnames(mm) <- c("frg_type_nr","stripped_sequence","relative_intensity.x",
"relative_intensity.y")
list.ms2 <- split(mm,as.factor(mm$stripped_sequence))
allCor<-unlist(sapply(list.ms2, FUN=function(x)
{if(nrow(x)>1 & length(unique(x[,3]))>1 & length(unique(x[,4]))>1) {cor(x[,3],x[,4],method="spearman")}}) )
ionCorGS <- NULL; rm(ionCorGS);
data(ionCorGS)
boxplot(allCor, ionCorGS, names=c("in study", "gold standard"),
col=c("darkgreen", "darkorange"),
main="Relative ion intensity correlation between libraries",outline=FALSE)
abline(h=0.8, col="red")
invisible(allCor)
}<file_sep>\name{plotErrorBarsLines}
\alias{plotErrorBarsLines}
\title{
Utility for clustering plots to plot lines and an overall trend
}
\description{
Prints faint lines for each profile, and a mean/error bars
}
\usage{
plotErrorBarsLines(v, barSizes, lines, labels = NULL, col = "blue", ylim, ...)
}
\arguments{
\item{v}{
Overall trend, to be printed solid, length n
}
\item{barSizes}{
Size of the error bars, length n
}
\item{lines}{
Matrix of n columns, and as many rows as lines
}
\item{labels}{
Labels to be printed on the x axis, length n
}
\item{col}{
Colour for main trend line
}
\item{ylim}{
Can specfy limits so several graphs are on the same scale
}
\item{\dots}{
Additional parameters to pass in
}
}
\details{
}
\value{
No returned value; plot only.
}
\references{
}
\author{
}
\note{
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\seealso{
\code{\link{help}}, ~~~
}
\examples{
mat = matrix(rnorm(100), 10)
plotErrorBarsLines(apply(mat,1,FUN=mean), apply(mat,1,FUN=sd),
lines=mat, col="red", main="A random plot", xlab="Some label")
}
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>
\name{buildSpectraLibPair}
\alias{buildSpectraLibPair}
\title{Build a spectra library by integrating a pair of spectrum libraries}
\usage{
buildSpectraLibPair(baseLib, extLib, hydroIndex, method = c("time", "hydro",
"hydrosequence"), includeLength = FALSE, labelBase = NA, labelAddon = NA,
formatBase = c("peakview", "openswath"), formatExt = c("peakview",
"openswath"), outputFormat = c("peakview", "openswath"),
outputFile = "extendedLibrary.txt", plot = FALSE,
clean = TRUE, merge = TRUE, parseAcc = TRUE, consolidateAccession = TRUE, ...)
}
\arguments{
\item{baseLib}{a base library data frame or file}
\item{extLib}{an external/addon library data frame or file}
\item{hydroIndex}{a data frame or file containing peptide hydrophobicity index}
\item{method}{a character string to specify the RT alignment method. One
of "time" (default), "hydro" and "hydrosequence" can be selected.}
\item{includeLength}{a logic value representing if include peptide
length as a feature for predicting retention time. Only applicable
when method is "hydro".}
\item{labelBase}{a character string to specify the labels of proteins from the base library}
\item{labelAddon}{a character string to specify the labels of proteins from the addon library}
\item{formatBase}{a character string denoting the file format of
base library file. One of "peakview" (default) and "opensswath"}
\item{formatExt}{a character string denoting the file format of
addon library file. One of "peakview" (default) and "opensswath"}
\item{outputFormat}{a character string denoting the file format of
the output integrated library. One of "peakview" (default) and "opensswath"}
\item{outputFile}{A character string to specify the sepctra library created}
\item{plot}{a logic value, representing if plots during processing
will be plotted or not}
\item{clean}{a logic value, representing if the input libraries will be
cleaned before integration. Default value is True.}
\item{merge}{a logic value, representing if the output will be the merged
library (default) or the adjusted add-on library.}
\item{parseAcc}{a logic value, repesenting if the protein accessions will be
parsed for consolidation.}
\item{consolidateAccession}{a logic value, representing if the protein
accessions will be consolidated to the base libary in the integrated
library. Default value is True.}
\item{\dots}{Additional parameters to pass in.}
}
\value{
A data frame of the integrated spectrum library
}
\description{
Build a spectra library by integrating a pair of spectrum libraries
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
Lib2_3 <- buildSpectraLibPair(libfiles[1], libfiles[2],
outputFormat="peakview", clean=TRUE, nomod=TRUE, nomc=TRUE)
}
<file_sep>\name{checkQuality}
\alias{checkQuality}
\title{Checking for the integration quality of two libraries}
\usage{
checkQuality(datBaseLib, datExtLib, ...)
}
\arguments{
\item{datBaseLib}{a data frame of the base library}
\item{datExtLib}{a data frame of the add-on library}
\item{\dots}{Additional parameters to pass in}
}
\value{
A list of quality indicators, including squared retention time (RT)
correlation coefficient, root mean squared errors of RT residuals,
and median of relative ion intensity correlation coefficient
}
\description{
Checking for the integration quality of two libraries
}
\examples{
libfiles <- paste(system.file("files",package="SwathXtend"),
c("Lib2.txt","Lib3.txt"),sep="/")
datBaseLib <- readLibFile(libfiles[1])
datExtLib <- readLibFile(libfiles[2])
res <- checkQuality(datBaseLib, datExtLib)
}
<file_sep>mlrGroup <-
function(mat, Group) {
Group = as.factor(Group)
if (length(Group) != ncol(mat)) stop("Matrix and group sizes don't match for mlr norm.");
lev.idx = lapply(levels(Group), FUN=function(g){which(Group == g)})
norm.list = lapply(lev.idx, FUN = function(i){mlrrep(mat[,i])});
# check same colnames?
norm.mat = matrix(NA, nrow(mat), ncol(mat))
colnames(norm.mat) = colnames(mat)
rownames(norm.mat) = rownames(mat)
for(j in 1:length(lev.idx)) norm.mat[,lev.idx[[j]]] = as.matrix(norm.list[[j]]$mat.norm)
mlrrep(norm.mat)
}
<file_sep>medianNorm <-
function(mat) {
med = apply(mat, 2, FUN = function(v){median(na.omit(v))})
mat.norm = sweep(mat, 2, med/max(med), FUN="/")
mat.norm
}
<file_sep>\name{readLibFile}
\alias{readLibFile}
\title{Load a spectrum library into a data frame}
\usage{
readLibFile(file, format = c("peakview", "openswath"), type = c("spectrum",
"hydro"), clean = TRUE, ...)
}
\arguments{
\item{file}{A file of a spectrum library, in .txt or .csv format, can be .gz files.}
\item{format}{A character string denoting the file format. One of "peakview" (default) and "openswath"}
\item{type}{A character string denoting the file type. One of "spectrum" (default) and "hydro"}
\item{clean}{A logic value, representing if the library will be cleaned.}
\item{\dots}{
Additional parameters to pass in
}
}
\value{
a data frame of the library with cleaning process
}
\description{
Load a spectrum library into a data frame
}
\examples{
file <- paste(system.file("files",package="SwathXtend"),"Lib1.txt",sep="/")
dat <- readLibFile(file)
}
<file_sep>###########################################################################
#' output a spectrum library into a PeakView format file
#' @param dat A data frame of a spectrum library
#' @param filename A character string for the name of the output.
#' @param nodup A logic value, indicating if remove duplicated
#' sprectrum (default)
#' @param format A character string representing the output format. One of
#' "peakview" (default) and "openswath".
#' @return a file with the specified file name (lib.txt as default) will be
#' saved under the current working directory
#' @examples
#' file <- paste(system.file("files",package="SwathXtend"),"Lib1.txt",sep="/")
#' dat <- readLibFile(file)
#' outputLib(dat)
############################################################################
outputLib <- function(dat, filename = "NewLib.txt", format = c("peakview", "openswath"), nodup = TRUE)
{
if(nodup) dat <- dat[!duplicated(dat),]
dat <- libraryFormat(dat)
format <- match.arg(format)
if(format == "peakview"){
dat.res <- dat
} else if (format == "openswath"){
PrecursorMz <- as.numeric(as.character(dat$Q1))
ProductMz <- as.numeric(as.character(dat$Q3))
Tr_recalibrated <- as.numeric(as.character(dat$RT_detected))
ProteinName <- dat$protein_name
GroupLabel <- as.factor(dat$isotype)
LibraryIntensity <- as.numeric(as.character(dat$relative_intensity))
PeptideSequence <- dat$stripped_sequence
FullUniModPeptideName <- dat$modification_sequence
UniprotID <- dat$uniprot_id
decoy <- as.factor(dat$decoy)
PrecursorCharge <- as.numeric(as.character(dat$prec_z))
FragmentType <- dat$frg_type
FragmentCharge <- as.numeric(as.character(dat$frg_z))
FragmentSeriesNumber <- as.numeric(as.character(dat$frg_nr))
dat.res <- data.frame(PrecursorMz,ProductMz,Tr_recalibrated,
ProteinName,GroupLabel,LibraryIntensity,
PeptideSequence,FullUniModPeptideName,
UniprotID,decoy,PrecursorCharge,
FragmentType,FragmentCharge,FragmentSeriesNumber)
} else {
stop("Wrong output format!")
}
write.table(dat.res, file = filename,sep="\t",quote=FALSE,row.names=FALSE)
} | dd3254bf5049f77a3945c2641dc9e015f2cff2d8 | [
"R"
] | 41 | R | Bioconductor-mirror/SwathXtend | b241ffd6c73ca7fefea249ad37dbd381b9673bdc | 3f646068ddfb3b55128f26214406b84ba0728d81 |
refs/heads/master | <repo_name>maxfortun/localgate<file_sep>/docker/files/root/init/save_routing.sh
#!/bin/bash
iptables-save | awk ' !x[$0]++' > /etc/sysconfig/iptables
ip link show|grep -o -P '(?<=\d:\s)[^:]+'|grep -v '^lo$' | while read link; do
routes=$(ip route show table $link 2>/dev/null)
if [ -n "$routes" ]; then
echo -n > /etc/sysconfig/network-scripts/route-$link
while read line; do
echo "$line table $link" >> /etc/sysconfig/network-scripts/route-$link
done <<< "$routes"
fi
rules=$(ip rule list 2>/dev/null | grep $link | sed 's/^[0-9]*:\s*//g')
if [ -n "$rules" ]; then
echo "$rules" > /etc/sysconfig/network-scripts/rule-$link
fi
done
<file_sep>/docker/files/root/init/client.sh
#!/bin/bash
# Used to switch outfacing vpn client endpoint
provider=$1
id=$2
proto=$3
files=$(find /etc/openvpn/client/ -type f -path "*$provider*$id*$proto*.ovpn" -print | sort)
count=$(echo "$files" | wc -l)
echo "$files"
echo $count
if [ "$count" -ne "1" ]; then
exit
fi
file=$files
cp "$file" /etc/openvpn/client.conf
echo -e "\n# original: $file" >> /etc/openvpn/client.conf
systemctl restart openvpn@client
<file_sep>/docker/files/root/init/initOpenVPN.sh
#!/bin/bash
wanHost="$1"
# https://www.digitalocean.com/community/tutorials/how-to-setup-and-configure-an-openvpn-server-on-centos-7
# CWD - current work dir
# SWD = script work dir
CWD=$(pwd)
SWD=$(dirname $0)
cd $SWD
SWD=$(pwd)
yum -y install epel-release
yum -y install openvpn easy-rsa policycoreutils-python iptables-services traceroute net-tools NetworkManager-config-routing-rules bind bind-utils iptables initscripts
systemctl mask firewalld
systemctl enable iptables
#systemctl stop firewalld
#systemctl start iptables
iptables --flush
# May want to replace this line with something more granular
# iptables -A INPUT -p udp -m state --state NEW -m udp --dport 1194 -j ACCEPT
# iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 1194 -j ACCEPT
ls -la /etc/sysconfig/iptables
iptables-save > /etc/sysconfig/iptables
cp server*.conf client*.ovpn learn-address.sh /etc/openvpn
# https://community.openvpn.net/openvpn/wiki/EasyRSA3-OpenVPN-Howto
mkdir -p /etc/openvpn/easy-rsa/keys
easyRSAVersion=$(ls -1 /usr/share/easy-rsa/|sort -V|tail -1)
cp -rf /usr/share/easy-rsa/$easyRSAVersion/* /etc/openvpn/easy-rsa
openSSLCFG=$(ls -1 /etc/openvpn/easy-rsa/openssl-*.cnf|sort -V|tail -1)
cp $openSSLCFG /etc/openvpn/easy-rsa/openssl.cnf
cd /etc/openvpn/easy-rsa
./easyrsa init-pki
./easyrsa --batch build-ca nopass
./easyrsa --batch --req-cn=server gen-req server nopass
./easyrsa --batch sign-req server server
./easyrsa --batch --req-cn=client gen-req client nopass
./easyrsa --batch sign-req client client
./easyrsa gen-dh
cd /etc/openvpn/easy-rsa/pki
cp dh*.pem ca.crt issued/server.crt private/server.key /etc/openvpn
$SWD/genOVPN.sh "$wanHost"
cat <<_EOT_ >> /etc/sysctl.conf
net.ipv4.ip_forward = 1
_EOT_
systemctl restart network.service
sed -i 's/ root / openvpn /g' /usr/lib/tmpfiles.d/openvpn.conf
chown openvpn:openvpn /var/run/openvpn/
systemctl -f enable openvpn<EMAIL>
systemctl -f enable openvpn@ser<EMAIL>
systemctl start openvpn@server<EMAIL>
systemctl start openvpn@servertcp.<EMAIL>
sed -i 's#listen-on port 53.*$#listen-on port 53 { 127.0.0.1; 10.8.1.1; };#g' /etc/named.conf
sed -i 's#allow-query .*$#allow-query { localhost; 10.8.1.0/24; };#g' /etc/named.conf
named-checkconf
systemctl -f enable named
systemctl start named
cat <<_EOT_
Run set_local_routing.sh then set_iptables.sh.
Test your config to make sure it works.
If everything is ok, then save config using save_routing.sh.
_EOT_
<file_sep>/docker/files/root/init/set_iptables.sh
#!/bin/bash
# https://community.openvpn.net/openvpn/wiki/BridgingAndRouting
#
cd $(dirname $0)
debug=${debug-echo}
LOCAL_IF=$1
VPNIN_IF=$2
VPNOUT_IF=$3
if [ -z "$VPNIN_IF" ]; then
echo "Usage to show commands: $0 <local> <vpn in> [vpn out]"
echo "Usage to run commands: debug= $0 <local> <vpn in> [vpn out]"
echo "Where ids are one of the following:"
ip link show|grep -o -P '(?<=\d:\s)[^:]+'|grep -v '^lo$'
exit
fi
. ./set_net_env.sh $LOCAL_IF
eval LOCAL_NETWORK=\$${LOCAL_IF}_network
eval LOCAL_PREFIX=\$${LOCAL_IF}_prefix
. ./set_net_env.sh $VPNIN_IF
eval VPNIN_NETWORK=\$${VPNIN_IF}_network
eval VPNIN_PREFIX=\$${VPNIN_IF}_prefix
# Allow traffic initiated from VPN to access LAN
$debug iptables -I FORWARD \
-i $VPNIN_IF -o $LOCAL_IF \
-s $VPNIN_NETWORK/$VPNIN_PREFIX -d $LOCAL_NETWORK/$LOCAL_PREFIX \
-m conntrack --ctstate NEW -j ACCEPT
if [ -z "$VPNOUT_IF" ]; then
VPNOUT_IF=$LOCAL_IF
fi
. ./set_net_env.sh $VPNOUT_IF
eval VPNOUT_NETWORK=\$${VPNOUT_IF}_network
eval VPNOUT_PREFIX=\$${VPNOUT_IF}_prefix
# Allow traffic initiated from LAN to access "the world"
$debug iptables -I FORWARD \
-i $LOCAL_IF -o $VPNOUT_IF \
-s $LOCAL_NETWORK/$LOCAL_PREFIX \
-m conntrack --ctstate NEW -j ACCEPT
# Allow traffic initiated from VPN to access "the world"
$debug iptables -I FORWARD \
-i $VPNIN_IF -o $VPNOUT_IF \
-s $VPNIN_NETWORK/$VPNIN_PREFIX \
-m conntrack --ctstate NEW -j ACCEPT
# Masquerade traffic from VPN to "the world" -- done in the nat table
$debug iptables -t nat -I POSTROUTING -o $VPNOUT_IF \
-s $VPNIN_NETWORK/$VPNIN_PREFIX -j MASQUERADE
# Masquerade traffic from LAN to "the world"
$debug iptables -t nat -I POSTROUTING -o $VPNOUT_IF \
-s $LOCAL_NETWORK/$LOCAL_PREFIX -j MASQUERADE
# Allow established traffic to pass back and forth
$debug iptables -I FORWARD \
-m conntrack --ctstate RELATED,ESTABLISHED \
-j ACCEPT
<file_sep>/bin/run.sh
#!/bin/bash
cd $(dirname $0)
. setenv.sh
./stop.sh
cd ../docker
PORT_PREFIX=20
PORTS=
while read dockerPort; do
hostPrefix=$PORT_PREFIX
hostPort=$hostPrefix$dockerPort
while [ "$hostPrefix" != "" -a "$hostPort" -gt "65535" ]; do
hostPrefix=${hostPrefix%?}
hostPort=$hostPrefix$dockerPort
done
PORTS="$PORTS -p $hostPort:$dockerPort"
done < <(grep -o 'EXPOSE[[:space:]]*[[:digit:]]*' Dockerfile|awk '{ print $2 }'|sort -fu)
docker system prune -f
docker run -itd -e container=docker --privileged --cap-add SYS_ADMIN --tmpfs /run -v /sys/fs/cgroup:/sys/fs/cgroup:ro $PORTS --name $NAME local/$NAME
<file_sep>/bin/setenv.sh
NAME=c7-localgate
<file_sep>/docker/files/root/init/set_local_routing.sh
#!/bin/bash
# In some configurations it is needed to explicitly route local traffic back to the requesting network interface
# Such as during the initial openvpn handshaking.
# this script needs to be executed only once.
cd $(dirname $0)
debug=${debug-echo}
link=$1
if [ -z "$link" ]; then
echo "Usage to show commands: $0 <id> [mark]"
echo "Usage to run commands: debug= $0 <id> [mark]"
echo "Where mark is optional and is a number"
echo "Where id is one of the following:"
ip link show|grep -o -P '(?<=\d:\s)[^:]+'|grep -v '^lo$'
exit
fi
. ./set_net_env.sh $link
eval gateway=\$${link}_gateway
mark=${2:-1}
echo "$link: mark $mark"
$debug iptables -t mangle -A PREROUTING -m conntrack --ctstate NEW -i $link -j CONNMARK --set-mark $mark
$debug iptables -t mangle -A OUTPUT -m connmark --mark $mark -j CONNMARK --restore-mark
table=$link
tableId=$(grep -P "^\d+\s+$table" /etc/iproute2/rt_tables|awk '{ print $1 }')
if [ -z "$tableId" ]; then
echo "$table: Table is missing"
tableId=$(grep -P '^\d' /etc/iproute2/rt_tables|grep -Pv '^0\s'|sort -n|head -1|awk '{ print $1 }')
tableId=$(( tableId-1 ))
echo "$tableId $table" >> /etc/iproute2/rt_tables
fi
echo "$table: Table $tableId"
$debug ip route add default via $gateway table $table
$debug ip rule add fwmark $mark table $table
<file_sep>/docker/files/root/init/set_net_env.sh
#!/bin/bash
# this script sets network interface env variables based on link name specified
link=$1
if [ -z "$link" ]; then
echo "Usage: source ${BASH_SOURCE[0]} <id>"
echo "Where id is one of the following:"
ip link show|grep -o -P '(?<=\d:\s)[^:]+'|grep -v '^lo$'
[ "${BASH_SOURCE[0]}" != "$0" ] && return || exit
fi
inet=$(ip address show $link | grep -P '^\s*inet\s[^\s]+')
ippr=$(echo $inet|awk '{ print $2 }')
ip=${ippr%%/*}
echo "$link: ip $ip"
if [ "$ip" != "$ippr" ]; then
prefix=${ippr##*/}
network=$(ipcalc -n $ippr|cut -d= -f2)
else
peerpr=$(echo $inet|awk '{ print $4 }')
network=${peerpr%%/*}
prefix=${peerpr##*/}
fi
echo "$link: prefix $prefix"
echo "$link: network $network"
gateway=$(ip route|grep -oP "(?<=via )[\d.]+(?= dev $link)"|sort -fu)
if [ -z "$gateway" ]; then
gateway=$ip
fi
echo "$link: Gateway $gateway"
export ${link}_link=$link
export ${link}_ip=$ip
export ${link}_prefix=$prefix
export ${link}_network=$network
export ${link}_gateway=$gateway
export ${link}_table=$link
<file_sep>/docker/files/root/init/genOVPN.sh
#!/bin/bash
wanHost="$1"
if [ -z "$wanHost" ]; then
wanHost=$(dig +short myip.opendns.com @resolver1.opendns.com)
fi
cd /etc/openvpn
PKI=/etc/openvpn/easy-rsa/pki
CA=$(cat $PKI/ca.crt)
CA=${CA//$'\n'/\\$'\n'}
CA=${CA//$'\r'/\\$'\r'}
PUB=$(cat $PKI/issued/client.crt)
PUB=${PUB//$'\n'/\\$'\n'}
PUB=${PUB//$'\r'/\\$'\r'}
PRI=$(cat $PKI/private/client.key)
PRI=${PRI//$'\n'/\\$'\n'}
PRI=${PRI//$'\r'/\\$'\r'}
for ovpn in *.ovpn; do
sed -i "s#your-publicly-accessible-ip-here#$wanHost#g" $ovpn
sed -i "s#... your ca cert here ...#$CA#g" $ovpn
sed -i "s#... your client public cert here ...#$PUB#g" $ovpn
sed -i "s#... your client private key here ...#$PRI#g" $ovpn
done
<file_sep>/docker/files/root/init/getPingStats.sh
#!/bin/bash
hosts=$*
if [ -z "$hosts" ]; then
hosts=$(ls | cut -d. -f1-3|sort -V -fu)
fi
for host in $hosts; do
ping -q -i .2 -c 4 $host | tail -1 | cut -d/ -f5 | xargs echo $host
done
| 1424cc1cd385be9b544440e4b5ac90ecd9b204db | [
"Shell"
] | 10 | Shell | maxfortun/localgate | 7cbbe5c04b5462450afe1f1d0c4fe1b70f944768 | 456f5f320b6e6a4b12062a8ffc52c4c6d5008af5 |
refs/heads/master | <file_sep>***MEMORY GAME***
Memory game is a easy to use fun game created with DOM API in JavaScript, including various elements of HTML and CSS. It is a simple game which tests the memoral grasp of a person. It is at large, is a card matching game suitable for people of all ages.
***USABILITY***
1. ***HOW TO PLAY THE GAME***
- Start by clicking any random card on the deck.
- Once clicked over, the card shall flip and reveal its contents
- Now click on the card that you think has got similar contents.
- After every two cards have been clicked "MOVES" increases by one.
An Illustration has been provided below:

2. ***What Happens If Don't Match*** - When the cards you clicked don't match, they just flip back over and continue the game by clicking any random card.
3. ***If the cards you selected match*** - Their color gets changed and the remain flipped over revealing thier contents

4. ***How Do you win*** - Once All the cards you have selected get matched, a new window pops up saying you have won the game with number of moves.
5. ***How do you restart the game*** - Click the reset button on the top right hand corner and the game shall reset along with the moves.
***KNOWN BUGS***
One of the bug that we noticed was that on clicking any of the three cards quickly the first card gets stuck. So to continue with the game just reset the game or reload the page.

[](https://forthebadge.com)
***AUTHOR: <NAME>***
<file_sep>function displayCard(e) {
if(e.target.classList == ("card")){
e.target.classList.add("open","show");
arr.push(e.target); //adds array to the container
match(e);
}
// this function flips the card to display its contents
}
function match(){
if(arr.length == 2){
if(arr[0].innerHTML == arr[1].innerHTML ){
arr[0].classList.add("match");
arr[1].classList.add("match");
arr = [];
congratulations(); // if two cards are same this functions assigns them the class match and changes their background color
}
else {
setTimeout( function () {
arr[0].classList.remove("open","show");
arr[1].classList.remove("open","show");
arr = [];
}, 400); // if two cards dont match this function turns them back
}
for(i = 0; i < moves.length; i++)
moves[i].innerHTML++; // this peice of code increments the number once every two cards are clicked
}
// this function checks for a match of the cards
}
function restartGame(){
let cardSelector = document.querySelectorAll('.card');
for ( var i = 0; i < cardSelector.length; i++){
cardSelector[i].classList.remove("open", "show", "match"); // selects the elements having class name match and removes the open, show and match class from the elements
}
for(i = 0; i < moves.length; i++)
moves[i].innerHTML = "0"; //this function resets the no of moves to zero
// this function Resets the game from the start
}
function congratulations() {
if(matchedCard.length == 16){
testContainer.style.display = "flex";
}
// this function displays once a user matches all the cards and a congratulatory note gets displayed
}
function reSet2 (){
document.getElementById('testContainer').style.display = "none";
let cardSelector = document.querySelectorAll('.card');
for ( var i = 0; i < cardSelector.length; i++){
cardSelector[i].classList.remove("open", "show", "match");
}
for(i = 0; i < moves.length; i++)
moves[i].innerHTML = "0";
// this function resets the game when play agaain element from the congratulations page is pressed
}
let card = document.querySelectorAll('.card')
let deck = document.querySelector('.deck');
let moves = document.querySelectorAll('.moves')
let reSet = document.querySelector('.restart')
let matchedCard = document.getElementsByClassName('match')
let testContainer = document.getElementById('testContainer')
let playAgain = document.querySelector('.playAgain')
deck.onclick = displayCard;
let arr = [];
reSet.onclick = restartGame;
playAgain.onclick = reSet2;
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
| 4b0700f5739990840293fd64bfc1509f09bf8c7e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | rajdeepgill05/memoryGame | 73bfe05ef5f0825b4df7942d86c874f6d748c541 | 84b3d44d8dd2e8b0ab38fa53eb9f1f3d7ca9ac1c |
refs/heads/master | <file_sep>rootProject.name = 'ReduxTeste'
include ':app'
<file_sep>import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';
import { connect } from 'react-redux';
class Card extends Component {
render() {
console.log(this.props);
return (
<View>
<Button
onPress={() => this.props.userSetName('Leonardo')}
title='button dispatch'
/>
<Button
onPress={() => this.props.userSetXamarin('Xamarin')}
title='button dispatch xamarin'
/>
<Text>{this.props.user.name}</Text>
</View>
);
}
}
const mapStateProps = (state) => {
return {
user: state.user
};
};
const mapDispatchProps = (dispatch) => {
return {
userSetName : function(data){
return dispatch({ type: 'USER_SET', payload: data, xamarin: 'não' });
},
userSetXamarin : function(data){
return dispatch({ type: 'USER_SET_XAMARIN', payload: data, xamarin: 'sim' });
}
}
}
export default connect(mapStateProps, mapDispatchProps)(Card);
| 09c4dddf34efc1872407e9eb6c817b08c7e2a155 | [
"JavaScript",
"Gradle"
] | 2 | Gradle | E-Sight/ReduxTeste | 724cd39f1701698e54340d0da2cb8ab962e52d68 | c7e67c182854701203446e7bb56e87386cadc109 |
refs/heads/master | <file_sep>import tbapy
import pandas as pd
import json
from datetime import datetime
import numpy
from ast import literal_eval
import numpy as np
tba = tbapy.TBA('<KEY>')
###############INITIAL DATA COLLECTION######################
teamsList = []
real_events = pd.read_csv('2018events.csv')
real_events = real_events['event_code'].values
# for i in range(0,20):
# teams = tba.teams(i)
# teams = json.dumps(teams)
# teams = pd.read_json(teams)
# teamsList.append(teams)
# i+=1
#
# all_teams = pd.concat(teamsList, ignore_index=True)
# # all_teams = all_teams[:50]
# #print(all_teams.columns.values)
# # # all_teams = all_teams[all_teams["team_number"] <= 7331]
#
# ############################### Drop useless columns############################################
# drop_list = ["lat","lng","address", 'city', 'country', 'gmaps_place_id', 'gmaps_url','home_championship', 'location_name', 'motto','name','postal_code','website']
# all_teams = all_teams.drop(drop_list, axis=1)
# # # # all_teams['test'],all_teams['test2']=[0,0]
# # # all_teams['opr'],all_teams['RP'],all_teams['district_points'],all_teams['W-L-T'],all_teams["match_points"] = [0,0,0,0,0]
#
#
# ####################GET ONLY THE TEAMS THAT HAVE PLAYED THIS YEAR#################################
# teamkeys = all_teams['key'].values
# for team in teamkeys:
# print(team)
# try:
# lastActiveYear = tba.team_years(team)[-1]
# except IndexError:
# lastActiveYear = 0
#
# if lastActiveYear != 2018:
# index = all_teams.index[all_teams['key'] == team].tolist()
# all_teams = all_teams.drop(index[0])
#
# # # all_teams.to_csv("all_teams.csv")
# #
all_teams = pd.read_csv('all_teams.csv')
# # print(all_teams)
# all_teams.to_csv('all_teams.csv')
########################ADD THE EVENTS OF EACH TEAM#################################################################
# eventSeries =[]
# for team in all_teams['key']:
# print(team)
# all_events = tba.team_events(team, year=2018)
# teamEvents = []
# for event in all_events:
# code = event['event_code']
# code = "2018"+str(code)
# if code in real_events:
# teamEvents.append(code)
# eventSeries.append(teamEvents)
#
# eventSeries = pd.Series(eventSeries)
# all_teams['events'] = eventSeries
# print(all_teams)
# all_teams.to_csv("all_teams.csv")
########################GET THE AVERAGE ADVANCED STATS OF EACH TEAM
all_teams_list = all_teams['key'].values
all_oprs =[]
all_dprs =[]
all_ccwms = []
for team in all_teams_list:
advanced_data = []
print(team)
teamEvents = all_teams[all_teams['key'] == team]['events'].values
teamEvents = map(literal_eval, teamEvents)
averageOPR = []
averageDPR = []
averageCCWM = []
for eventList in teamEvents:
OPRs = []
DPRs = []
CCWMs = []
for event in eventList:
try:
eventData = tba.event_oprs(event)
try:
try:
OPRs.append(eventData.oprs[team])
DPRs.append(eventData.dprs[team])
CCWMs.append(eventData.ccwms[team])
except AttributeError:
print(str(event) + " has bad data")
except KeyError:
#for some reason the team was registered for the event but did'nt go i think
print("Got key error for " + str(team) + "at " + str(event))
except TypeError:
print("Event hasn't happended yet")
try:
averageOPR = sum(OPRs)/float(len(OPRs))
averageDPR = sum(DPRs) / float(len(DPRs))
averageCCWM = sum(CCWMs) / float(len(CCWMs))
except ZeroDivisionError:
print(team + " has not played any events yet, but are registered for an upcoming one")
all_oprs.append(averageOPR)
all_dprs.append(averageDPR)
all_ccwms.append(averageCCWM)
all_teams['OPR'] = all_oprs
all_teams['DPR'] = all_dprs
all_teams['CCWM'] = all_ccwms
all_teams.to_csv("all_teams.csv")
# # testTeam = all_teams[:1]
# # print(testTeam)
# # team = testTeam['key']
# # events = list(testTeam['events'].values)
# # print(events[0][0])
# # #get opr
# # print(tba.event("2018miket"))
######################GET WINS, LOSSES, TIES, and TOTAL RANKING POINTS#################################
# all_teams = pd.read_csv('all_teams.csv')
# events = all_teams['events'].values
# events = map(eval, events)
# week0Events = tba.events(2018)
# week0Events = json.dumps(week0Events)
# week0Events = pd.read_json(week0Events)
# event_codes = week0Events['event_code']
# # event_codes= event_codes.values
# end_dates = week0Events['end_date']
# # end_dates = end_dates.values
# # week0Events = week0Events['event_code', 'end_date']
# realEvents = pd.concat([end_dates, event_codes], axis=1)
# realEvents.columns = ['end_date', 'event_code']
# realEvents['end_date'] = realEvents['end_date'].apply(lambda x: pd.to_datetime(x, infer_datetime_format=True))
# week1Start = datetime(2018,2,28)
# realEvents = realEvents[realEvents['end_date']>week1Start]
# realEvents = realEvents.sort_values(by=['end_date'])
# realEvents = realEvents['event_code'].values
# all_events = []
# for event in realEvents:
# event = "2018"+str(event)
# all_events.append(event)
# all_events = pd.DataFrame(all_events)
# all_events.columns = ['event_code']
# print(all_events)
# all_events.to_csv('2018events.csv')
# event_ranking = tba.event_rankings('2018miket')
# #event_ranking = json.dumps(event_ranking, indent=4, sort_keys=True)
# print(event_ranking)
<file_sep>import tbapy
import pandas as pd
import json
tba = tbapy.TBA("<KEY>")
wpi = tba.event_teams("2018mawor")
wpi = json.dumps(wpi)
wpi = pd.read_json()
print wpi.head(5)
<file_sep>import pandas
from pandas import DataFrame, read_csv
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display, HTML
from gmplot import gmplot
import gmaps
import gmaps.datasets
import gmaps.datasets
import tbapy
import json
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
import seaborn as sns
from clustergrammer_widget import *
%matplotlib inline
tba = tbapy.TBA('<KEY>')
gmaps.configure(api_key='<KEY>')
figure_US = {
'width': '1000px',
'height': '600px',
'border': '1px solid black',
'padding': '1px'
}
#['Alaska', 66.0685, -152.2782]
#['Hawaii', 21.094318, -157.498337]
stateCoords = [['Alabama', 32.806671, -86.791130], ['Arizona', 34.729759, -111.431221],
['Arkansas', 34.969704, -92.373123], ['California', 36.116203, -119.681564], ['Colorado', 39.059811, -105.311104],
['Connecticut', 41.597782, -72.755371], ['Delaware', 38.989, -75.507141], ['Florida', 27.766279, -81.686783],
['Georgia', 33.040619, -83.643074], ['Idaho', 44.240459, -114.478828],
['Illinois', 40.349457, -88.986137], ['Indiana', 39.849426, -86.258278], ['Iowa', 42.011539, -93.210526],
['Kansas', 38.526600, -97.626486], ['Kentucky', 37.668140, -84.670067], ['Louisiana', 31.169546, -92.367805],
['Maine', 45.393947, -69.081927], ['Maryland', 39.063946, -76.802101], ['Massachusetts', 42.230171, -71.530106],
['Michigan', 43.326618, -84.536095], ['Minnesota', 45.694454, -94.300192], ['Mississippi', 32.741646, -89.678696],
['Missouri', 38.456085, -92.288368], ['Montana', 46.921925, -109.454353], ['Nebraska', 41.325370, -98.868082],
['Nevada', 39.813515, -117.055374], ['New Hampshire', 43.452492, -71.563896], ['New Jersey', 40.298904, -74.521011],
['New Mexico', 34.840515, -106.248482], ['New York', 43.165726, -74.948051], ['North Carolina', 35.630066, -79.006419],
['North Dakota', 47.528912, -99.784012], ['Ohio', 40.388783, -82.764915], ['Oklahoma', 35.565342, -96.928917],
['Oregon', 43.872021, -120.870938], ['Pennsylvania', 40.590752, -77.209755], ['Rhode Island', 41.680893, -71.511780],
['South Carolina', 33.856892, -80.945007], ['South Dakota', 44.299782, -99.438828], ['Tennessee', 35.747845, -86.692345],
['Texas', 31.054487, -98.863461], ['Utah', 40.150032, -111.862434], ['Vermont', 44.045876, -72.710686],
['Virginia', 37.769337, -78.169968], ['Washington', 47.400902, -121.490494], ['West Virginia', 38.491226, -80.954453],
['Wisconsin', 44.268543, -89.616508], ['Wyoming', 42.755966, -107.302490]]
values = [10, 20, 40, 25, 15, 7, 30, 22, 12, 9, 10, 20, 40, 25, 15, 7, 30, 22, 12, 9, 10, 20, 40, 25, 15, 7, 30, 22, 12, 9,
10, 20, 40, 25, 15, 7, 30, 22, 12, 9, 10, 20, 40, 25, 15, 7, 30, 22, 12, 9]
allData = pandas.read_csv("all_data.csv")
champTeams = pandas.read_csv("champsTeams.csv")
states = pandas.DataFrame( allData["state_prov"])
states = states.rename(index=str, columns={"state_prov": "State"})
champs = champTeams.rename(index=str, columns={"state_prov": "State"})
# print(states)
#group the data by state and get the count
state2 = pandas.DataFrame({'count' : states.groupby( ["State"] ).size()})
champs2 = pandas.DataFrame({'champ count': champs.groupby(["State"]).size()})
# display(HTML(state2.to_html()))
print(champs2)
data = pandas.DataFrame(stateCoords, columns=['State', 'Latitude', 'Longitude'])
data = data.set_index('State')
# display(HTML(data.to_html()))
value = pandas.DataFrame(values, columns=['Size'])
result = data.join(state2)
result = result.join(champs2)
result = result.fillna(0)
display(HTML(result.to_html()))
fig = gmaps.figure(layout = figure_US)
maxNum = result['champ count'].max()
for index, row in result.iterrows():
location = pandas.DataFrame([[row[0], row[1]]])
size = int(row[2] / 5)
if size == 0:
size = 1
champ = row[3]
newValue = int((champ * 255) / maxNum)
r = newValue
g = 0
b = 255 - newValue
string1 = ('rgba(%d, %d, %d, 0.7)'% (r, g, b))
string2 = ('rgba(%d, %d, %d, 0)'% (r, g, b))
kfc_layer = gmaps.symbol_layer(
location, fill_color=string1,
stroke_color=string2, scale=size
)
fig.add_layer(kfc_layer)
fig
teamData = allData[["key", "OPR", "DPR", "CCWM", "RankingPoints", "Wins", "Losses", "Ties"]]
teamData = teamData.set_index("key")
# print(champTeams)
champKey = champTeams.set_index("key")
final = champKey.join(teamData)
final = final[["OPR", "DPR", "CCWM", "RankingPoints", "Wins", "Losses", "Ties"]]
print(final)
net = Network(clustergrammer_widget)
net.load_df(final[["CCWM", "RankingPoints", "Wins", "Ties"]])
net.cluster(enrichrgram=False)
net.widget()
df = pandas.read_csv('all_data.csv')
df = df[['key','OPR', 'CCWM', 'ClimbPoints', 'AutoPoints', 'OwnershipPoints', 'VaultPoints' ]]
champsTeamList = pandas.read_csv('champsTeams.csv')
champsTeamList = champsTeamList['key'].values
df = df[df['key'].isin(champsTeamList)]
df = df.set_index('key')
keyValues = df.index.values
print(keys)
print(df)
cols = list(df)
test = df[cols[1:]]
print(test.shape)
from sklearn import preprocessing
x = df.values #returns a numpy array
print(x.shape)
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
result= pandas.DataFrame(x_scaled)
print(result.head())
#team_name = pandas.DataFrame(team_name)
#print(team_name.shape)
#result = pandas.concat([team_name, df], axis=1)
#print(df.columns)
#result = result.set_index('key')
#print(df.head())
cos = euclidean_distances(result)
x_normed = cos / cos.max(axis=0)
print(cos)
keys = pandas.Series(keyValues)
keys = keys.rename('key')
frame = pandas.DataFrame(cos, columns=keyValues )
# print(keys.head)
frame = pandas.concat([frame,keys], axis=1)
frame = frame.set_index('key')
print(frame)
net.load_df(frame[:100])
net.cluster(enrichrgram=False)
net.widget()
<file_sep>Team members: <NAME>, <NAME>, <NAME>, <NAME>
<file_sep>import tbapy
import pandas as pd
import json
import numpy as np
tba = tbapy.TBA('<KEY>')
# ######################GET WINS, LOSSES, TIES, and TOTAL RANKING POINTS#################################
# all_teams = pd.read_csv('all_teams.csv')
# events = pd.read_csv('2018events.csv')
# events = events['event_code'].values
# events = events
# #events = map(eval, events)
# statistics = pd.DataFrame()
# for event in events:
# print(event)
# event_ranking = tba.event_rankings(event)
# event_ranking = json.dumps(event_ranking, indent=4, sort_keys=True)
# # print (event_ranking[1])
#
# obj = json.loads(event_ranking)
# keys = obj.keys()
# # print(keys)
# # print(obj['sort_order_info'])
#
# parkPoints = 1
# autoPoints = 2
# ownershipPoints = 3
# vaultPoints = 4
#
# all_ranks = obj['rankings']
# #print(all_ranks[1]['sort_orders'][1])
# # print (len(obj['rankings']))
# # rankings = json.loads(obj['rankings'])
# # print (rankings.keys())
#
#
# """
# What Tom wants: losses, wins, ties and the extra stats number
# """
# all_losses = []
# all_wins = []
# all_ties = []
# all_team_key = []
# all_extra_stats_no = []
# all_park = []
# all_auto = []
# all_ownership = []
# all_vault = []
# try:
# for objects in all_ranks:
# # print (objects['team_key'])
# # print (objects['team_key'])
# all_team_key.append(objects['team_key'])
# all_extra_stats_no.append(objects['extra_stats'][0])
# all_wins.append(objects['record']['wins'])
# all_losses.append(objects['record']['losses'])
# all_ties.append(objects['record']['ties'])
# try:
# all_park.append(objects['sort_orders'][parkPoints])
# all_auto.append(objects['sort_orders'][autoPoints])
# all_ownership.append(objects['sort_orders'][ownershipPoints])
# all_vault.append(objects['sort_orders'][vaultPoints])
# except IndexError:
# pass
# # print (all_team_key)
# #print(all_extra_stats_no)
# # print (all_wins)
# # print (all_ties)
# # print (all_losses)
#
# df = pd.DataFrame(
# {'TeamKey': all_team_key,
# 'RankingPoints': all_extra_stats_no,
# 'Wins': all_wins,
# 'Losses': all_losses,
# 'Ties': all_ties,
# "ClimbPoints": all_park,
# "AutoPoints": all_auto,
# "OwnershipPoints": all_ownership,
# "VaultPoints": all_vault
# }, columns=["TeamKey","RankingPoints","Wins","Losses","Ties", "ClimbPoints","AutoPoints","OwnershipPoints","VaultPoints"])
# df = df.sort_values("RankingPoints", ascending=False)
# statistics = pd.concat([statistics, df])
# except TypeError:
# pass
#
# print(statistics)
# statistics.to_csv("TeamStatistics.csv", index=False )
#
# statistics = pd.read_csv('TeamStatistics.csv')
# statistics = statistics.groupby(["TeamKey"]).mean()
# teams = pd.read_csv('all_teams.csv')
# teams = teams.set_index('key')
# teams = teams.join(statistics)
# teams = teams.dropna()
# teams.to_csv("all_data.csv")
#
champs = ['2018tur','2018hop','2018gal','2018roe','2018carv','2018new','2018arc','2018cars','2018cur','2018tes','2018dar','2018dal']
champsTeams = []
for division in champs:
teams = tba.event_teams(division)
teams = json.dumps(teams)
teams = pd.read_json(teams)
champsTeams.append(teams)
goodTeams = pd.concat(champsTeams, ignore_index=True)
print(goodTeams.columns)
goodTeams = goodTeams[['key','state_prov']]
goodTeams = goodTeams.set_index('key')
goodTeams.to_csv("champsTeams.csv")
print(goodTeams.head) | 527376619809da6e55d383a1e21c79d532118bde | [
"Python",
"Text"
] | 5 | Python | alexemrick/DS3001 | b9b3fca1962f38cc0c6ecf3b81bca8d504ec289c | 5aa968e7c9139caba522043e10dca59b4e141301 |
refs/heads/main | <file_sep>import React from 'react'
import './DisplayMessage.css';
import {
BrowserRouter as Router,
Link
} from "react-router-dom";
export default function DisplayMessage({message}) {
const displayMessage= () => {
if(message !== 'Invalid Url' || message !== null ){
return <Link target="_blank" to={'//'+message}>{message}</Link>
}else{
return <p>{message}</p>
}
}
return (
<div className="message-wrapper">
<Router>
{displayMessage()}
</Router>
</div>
)
}
<file_sep>import React from 'react'
import './Footer.css'
import GitHubIcon from '@material-ui/icons/GitHub';
export default function Footer() {
return (
<footer>
Created By <NAME> <a target="_blank" rel="noreferrer" href="https://github.com/prashantrayamajhi"><GitHubIcon size="large" /></a>
</footer>
)
}
<file_sep>import React from "react";
import Navbar from './../components/Navbar/Navbar';
import InputBar from './../components/Inputbar/Inputbar'
import Footer from './../components/Footer/Footer';
export default function App() {
return (
<div>
<Navbar />
<InputBar />
<Footer />
</div>
);
}
<file_sep>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import {BrowserRouter as Router} from 'react-router-dom';
import './Navbar.css'
export default function SearchAppBar() {
return (
<Router>
<AppBar position="static">
<Toolbar>
<Typography variant="h5" noWrap>
Shorter URL
</Typography>
</Toolbar>
</AppBar>
</Router>
);
}
| 16b4aa497a076f6c69c8be9eac56d2af496abd28 | [
"JavaScript"
] | 4 | JavaScript | prashantrayamajhi/url-shortener-client | c7b6f0c2f8b4b43d03a0f9910ed57d5cd178212f | b217971b3a7f1d9cedeebb2039e1ec5f544da8a2 |
refs/heads/master | <repo_name>ugurcf/KartEslemeOyunu<file_sep>/memoryGame1/memoryGame1/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace memoryGame1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
byte islem = 0; //başa dönmek için
byte kalan = 8; // kalan eşlenmemiş kart
int sure=0; //timer ayarları
PictureBox oncekiResim;
void resimleriSifirla()
{
foreach(Control x in this.Controls)
{
if(x is PictureBox)
{
(x as PictureBox).Image = Properties.Resources._0;
}
}
}
void tagDagit() //kartlara tag numarası vermek için fonk
{
int[] sayilar = new int[16];
Random rastgele = new Random();
byte i = 0;
while(i<16)
{
int rast = rastgele.Next(1, 17);
if(Array.IndexOf(sayilar, rast)==-1)
{
sayilar[i] = rast;
i++;
}
}
for(byte a=0; a<16; a++) //16 kart var ama 8 resim 2 tane gerekiyor eşlemej için o yüzden 8 çıkıyoruz
{
if (sayilar[a] > 8) sayilar[a] -= 8;
}
byte b = 0;
foreach(Control x in this.Controls)
{
if(x is PictureBox)
{
x.Tag = sayilar[b].ToString();
b++;
}
}
}
void taglariSifirla() //yeni oyuna geçince hepsinin 0'lanması için
{
foreach (Control x in this.Controls)
{
if (x is PictureBox)
{
(x as PictureBox).Tag = "0";
}
}
}
void karsilastir(PictureBox onceki, PictureBox sonraki)
{
if(onceki.Tag.ToString()==sonraki.Tag.ToString())
{
Application.DoEvents();
System.Threading.Thread.Sleep(500);
onceki.Visible = false;
sonraki.Visible = false;
kalan--;
if (kalan == 0)
{
left.Text = "Tebrikler Kazandınız!";
}
else
{
left.Text = "Kalan = " + kalan; /*left labelin adı*/
}
}
else
{
Application.DoEvents();
System.Threading.Thread.Sleep(500);
onceki.Image = Image.FromFile("0.png");
sonraki.Image = Image.FromFile("0.png");
}
}
private void Form1_Load(object sender, EventArgs e)
{
resimleriSifirla();
taglariSifirla();
tagDagit();
lblTime.Text = Convert.ToString(sure);
timer1.Start();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
PictureBox simdikiResim = (sender as PictureBox);
simdikiResim.Image = Image.FromFile((sender as PictureBox).Tag.ToString() + ".png");
if(islem==0)
{
oncekiResim = simdikiResim;
islem++;
}
else
{
if(oncekiResim==simdikiResim)
{
MessageBox.Show("Bu kartı zaten seçmiştiniz.");
islem = 0;
oncekiResim.Image = Image.FromFile("0.png");
}
else
{
karsilastir(oncekiResim, simdikiResim);
islem = 0;
}
}
}
void goster()
{
foreach(Control x in this.Controls)
{
if(x is PictureBox)
{
(x as PictureBox).Image = Image.FromFile(x.Tag.ToString() + ".png");
}
}
}
void gizle()
{
foreach (Control x in this.Controls)
{
if(x is PictureBox)
{
(x as PictureBox).Image = Image.FromFile("0.png");
}
}
}
private void btnGoster_Click(object sender, EventArgs e)
{
goster();
Application.DoEvents();
System.Threading.Thread.Sleep(500);
gizle();
islem = 0;
}
void visibleAc()
{
foreach(Control x in this.Controls)
{
if(x is PictureBox)
{
(x as PictureBox).Visible = true;
}
}
}
private void btnYeniOyun_Click(object sender, EventArgs e)
{
resimleriSifirla();
taglariSifirla();
tagDagit();
visibleAc();
kalan = 8;
islem = 0;
if (islem == 0)
{
timer1.Stop();
sure = 0;
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
sure = sure + 1;
lblTime.Text = Convert.ToString(sure);
if (kalan == 0)
{
timer1.Stop();
}
}
}
}
| ce6feaf43bfc86bdf286d5fa5db84b5120d3f417 | [
"C#"
] | 1 | C# | ugurcf/KartEslemeOyunu | 03d9f36cc02928629b79d3c1c84bd409964c84f1 | a8bdd8c9687ff4b6984b2416967b5c7fe45efda4 |
refs/heads/main | <file_sep># Fully_Functional_Notepad_Java
This is my Notepad/ Text Editor design with GUI. I built undo operation in two ways. One of them Command Design Pattern
<file_sep>
package Notepad;
/**
*
* @author osman
*/
public abstract class UndoableCommand implements ICommand {
public abstract void Undo();
}
<file_sep>package Notepad;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import java.util.Iterator;
public class Operations {
//NotepadGui'nin temel operasyonları Operations() class'ı altında toplandı.
//Upgrade etmek istenildiğinde çok kolay bir şekilde yapılabilir.
//Tüm operasyonlar bir interface'de toplanabilirdi fakat bu tercih edilmedi.
//İstenirse her biri ayrı bir nesne şeklinde olup bir interface'e bağlanabilir.
//Kullanıcı bir text dosyası açmak istediğinde bu komut çalışıyor.
public void Open(NotepadGui n){
n.getOpen().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fc=new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(n.getM1());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//Scanner zaten kendisi Iterator interface'ini implement ettiği için burada iterator kullanmama gerek yok.
Scanner reader;
try {
reader = new Scanner(file);
while(reader.hasNextLine()){
String line = reader.nextLine();
//StyledDocument doc = textArea.getStyledDocument();
//doc.insertString(returnVal, line, as);
n.getTextArea().append(line);
n.getTextArea().append("\n");
}
reader.close();
} catch (FileNotFoundException ex) {
n.getTextArea().setText("Dosya açılamadı...");
System.out.println("Dosya açılamadı...");
}
}
}
});
}
//Notepad textArea'yı sıfırlayan metot.
public void NewMenuItem(NotepadGui n){
n.getNew().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
n.getTextArea().setText("");
n.getStack().clear();
}
});
}
//Kullanıcı menüden Quit yapmak isterse programı kapatan metot.
public void Close(NotepadGui n){
n.getQuit().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
}
//Kullanıcı yazdığı text dosyasını kaydetmek istediğinde çalışan metot.
public void Save(NotepadGui n){
n.getSave().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try{
JTextArea inputroute=new JTextArea("");
String fileName = JOptionPane.showInputDialog("Enter file name");//String finalFileName = fileName.getText();
if(fileName.isEmpty()){
JOptionPane.showMessageDialog(new JFrame(), "Kaydetmek için bir dosya adı giriniz!");
}
else{
FileWriter outFile = new FileWriter(fileName +".txt",true);
outFile.write(inputroute.getText());
n.getTextArea().write(outFile);
outFile.close();
}
} catch(FileNotFoundException e){
Component f = null;
JOptionPane.showMessageDialog(f,"File not found.");
} catch(IOException e){
Component f = null;
JOptionPane.showMessageDialog(f,"Error.");
}
}
});
}
//Normalde textArea'yı dinleyen metot burada. Fakat command tasarım deseni istendiği için buradaki kod kullanılmadı. (NotepadGui constructor'una bakabilirsiniz)
// Backspace ve space tuşlarına duyarlı bir metot. Yani siz hata yaptığınızda düzeltmek için silme tuşuna bastığınızda üzeri boyanmış olan hatalı kelimelerinizin
//boyalarını kaldırarak sizin daha rahat görmenizi sağlıyor. Ayrıca hata kontrolünü ise space tuşuna duyarlı yaptığımız için siz kelimenizi tamamlayıp space
//tuşuna basmadan hata kontrolünü gerçekleştirmiyoruz. Diğer türlüsü kaynak israfı olurdu ve hatalara sebebiyet verirdi.
//Bununla birlikte hata boyama işlemi de space tuşuna duyarlı bir şekilde yapılmıştır.
public void textAreaListener(NotepadGui n){
n.getTextArea().addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent ke) {
n.getStack().push((char)ke.getKeyChar());
//Kullanıcı yanlış kelimeyi düzeltirken kelimedeki highlight ı kaldırır. Görülmesi kolaylaşır
if((int)ke.getKeyChar()==8){
//System.out.println("backspace!!!!");
n.getTextArea().getHighlighter().removeAllHighlights();
n.getStack().clear();
for(int i=0;i<n.getTextArea().getText().length();i++){
n.getStack().push(n.getTextArea().getText().charAt(i));
}
}
hatalariBoya(n);
//System.out.println(highlightTag);
if(n.getHighlightTag()!= null){
n.getTextArea().getHighlighter().removeHighlight(n.getHighlightTag()); // Kullanıcı tekrar yazmaya başladığında arama yapılmış olan mavi highlightları siler
}
char ch = ke.getKeyChar();
InputMap imap = n.getTextArea().getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("SPACE"), "spaceAction");
ActionMap amap = n.getTextArea().getActionMap();
amap.put("spaceAction", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
//System.out.println("Space Pressed: " + textArea.getText());
try {
errorCheck(n);
} catch (IOException ex) {
System.out.println("Bilinmeyen bir hata meydana geldi.");
}
}
});
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
});
}
//Bu metot çağırıldığında textArea içindeki yazılı metini bir String olarak alıp üzerinde sözlük ile kontrol edilip hataliKelimeler listesinde
//tutulan kelimeleri aldığı string üzerindeki kelime offset'ine göre textArea'da boyama yapıyor.
public void hatalariBoya(NotepadGui n){
String tempTextAreaStr = new String(n.getTextArea().getText());
Highlighter.HighlightPainter painter3 =
new DefaultHighlighter.DefaultHighlightPainter( new Color(255, 192, 203));
if(!n.getHataliKelimeler().isEmpty()){
//Iterator kullanıldı-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Iterator<String> it = n.getHataliKelimeler().iterator();
int indexForIterator =0;
while(it.hasNext()){
String temp = it.next();
int offset = tempTextAreaStr.indexOf(n.getHataliKelimeler().get(indexForIterator));
int length = n.getHataliKelimeler().get(indexForIterator).length();
while(offset != -1){
try {
//Burada böyle bir if bulunmöasının sebebi : highlight'ı bir geriye uygulamayınca highlight takılı kalıyor
//ve ne yazılırsa yazılsın kurtulamıyorsunuz. Bu yüzden 2 geriden geliyor. İlk başta kelimenin hepsini kaplamıyor ama siz bir karakter daha
//yazdığınızda, son harfi haghlight olmamış kelimeyi de kapatmış oluyoruz :)
if(tempTextAreaStr.length() >=offset+length+1){
n.getTextArea().getHighlighter().addHighlight(offset, offset + length, painter3);
offset = tempTextAreaStr.indexOf(n.getHataliKelimeler().get(indexForIterator), offset+1);
}
else{
n.getTextArea().getHighlighter().addHighlight(offset, offset + length-1, painter3);
offset = tempTextAreaStr.indexOf(n.getHataliKelimeler().get(indexForIterator), offset+1);
}
} catch (BadLocationException ex) {
//System.out.println("HATA!");
}
}
indexForIterator++;
}
}
}
//Girilen karakterin integer olup olmadığını kontrol ediyor.
static boolean isInt(String s) // assuming integer is in decimal number system
{
for(int a=0;a<s.length();a++)
{
if(a==0 && s.charAt(a) == '-') continue;
if( !Character.isDigit(s.charAt(a)) ) return false;
}
return true;
}
//TextArea'daki kelimeleri alıp sözlükteki kelimelerle karşılaştırıyor. Single transposition varsa düzeltiyor.
public void errorCheck(NotepadGui n) throws IOException{
String text = new String(n.getTextArea().getText());
String[] dizi = text.split("\\s");
//Array Collections interface'ini implement etmediği için burada iterator
//kullanmak mantıksız olur.
for (int i = 0; i < dizi.length; i++) {
if (dizi[i].contains(".")) {
dizi[i] = dizi[i].replace(".", "");
}
if (dizi[i].contains(",")) {
dizi[i] = dizi[i].replace(",", "");
}
if (dizi[i].contains(";")) {
dizi[i] = dizi[i].replace(";", "");
}
if (dizi[i].contains(":")) {
dizi[i] = dizi[i].replace(":", "");
}
if (dizi[i].contains("!")) {
dizi[i] = dizi[i].replace("!", "");
}
if (dizi[i].contains("?")) {
dizi[i] = dizi[i].replace("\\?", "");
}
// dizi listesinde textteki bütün kelimeler tek tek mevcut, noktalama işaretlerinden arındırıldı
}
int uzunluk = dizi.length;
for (int t = 0; t < uzunluk; t++) {
dizi[t] = dizi[t].toLowerCase();
}
ArrayList<String> words = new ArrayList<String>();
//BufferedReader'ı iterable yapmış birkaç örnek gördüm fakat o zaman
//kendi custom BufferedReaderIterable class'ımızı oluşturmamuz gerekirdi.
//
BufferedReader oku;
try {
oku = new BufferedReader(new FileReader("sözlük.txt"));
boolean state = true;
while (state) {
String satir = oku.readLine();
if (satir != null) {
words.add(satir);
} else {
state = false;
} // while döngüsü ile words.txt dosyasındaki kelimeler arrayliste atıldı
}
int hatayazdirSayisi =1;
//Burada array gezildiği için bunu iterable yapmıyorum.
for (int a = 0; a < uzunluk; a++) {
if (words.contains(dizi[a]) || isInt(dizi[a]) == true) {
//System.out.println(dizi[a] + " kelimesi sözlük.txt dosyasında vardır (veya integer değerdir).");
//Performans iyileştirmesi için notepad açık olduğu sürece bir static final bir değişkende tutulabilirdi.
//Çok uzun bir dosya olmadığı için gerek duyulmadı.
} else {
ArrayList<String> kontrollist = new ArrayList<String>();
for (int b = 0; b < words.size(); b++) {
if (words.get(b).length() == dizi[a].length()) {
kontrollist.add(words.get(b));
}
}//aynı uzunlukta kelimeler kontrollistte
//karmaşıklık üstel olarak artmasın diye önce önce aynı uzunluktaki kelimeler bulundu.
//Iterator kullanımı-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Iterator<String> it = kontrollist.iterator();
int indexForIterator=0;
while(it.hasNext()){
String tempForIterate = it.next();
int hatasay=0;
for (int m=0; m<kontrollist.get(indexForIterator).length();m++){
if(kontrollist.get(indexForIterator).charAt(m) != dizi[a].charAt(m)){
hatasay++;
}
}
if(hatasay==2){
//Hata sayısı single tranposition olabilecek stringler olabilir fakat gerçekte bambaşka kelime olabilir.
//Örnek olarak Today. otday şeklinde yazılırsa 2 hatalı char bulunur ve bu single transpositiondır ve otomatik düzeltilir.
//peki modey gibi bir string olsaydı ne olurdu. Bu da 2 hatadan dolayı single tranposition olarak görülebilirdi.
//Bunu engellemek için stringlerdeki karakterler sıralandı ve bir kontrol daha yapıldı.
char[] hatalikelime = dizi[a].toCharArray();
Arrays.sort(hatalikelime);
char[] dogrukelime = kontrollist.get(indexForIterator).toCharArray();
Arrays.sort(dogrukelime);
int sayac=0;
for(int p=0;p<dogrukelime.length;p++){
if(dogrukelime[p]==hatalikelime[p]){
sayac++;
}
}
if(sayac==dogrukelime.length){
String dogruKelimeStr = kontrollist.get(indexForIterator);
String eskiKelime = dizi[a];
String tempTextAreaStr = new String(n.getTextArea().getText());
tempTextAreaStr = tempTextAreaStr.replace(eskiKelime, dogruKelimeStr);
n.getTextArea().setText(tempTextAreaStr);
hatalariBoya(n);
}
}
indexForIterator++;
}
n.getHataliKelimeler().add(dizi[a]);
hatalariBoya(n);
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(new JFrame(), "Sözlük dosyası okunurken hata meydana geldi!");
}
// words.txt dosyasındaki kelimelerin atılacağı arraylist tanımlandı
}
//geri alma işlemi için kullanılan metot. Stack kullanılıyor bunun için
// Command tasarım deseniyle gerçekleştirimi için yorum satırına alıyorum.
public void undo(NotepadGui n){
n.getUndoButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if(n.getTextArea().getText().isEmpty()){
JOptionPane.showMessageDialog(new JFrame(), "Daha fazla geri alma işlemi yapılamaz!");
}
else{
n.getStack().pop();
String temp= new String(n.getStack().realCopy());
n.getTextArea().setText(temp);
}
}
});
}
//String change tuşuna bastığınızda yeni bir frame açıyor. oradaki işlemler için bu frame kullanılıyor. Tüm olası hata kontrolleri handle edildi.
public void stringChangeFrame(String str,NotepadGui n){
n.getChangeStrButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
JDialog changeDialog = new JDialog(n.getFrame());
changeDialog.setSize(570, 100);
changeDialog.setResizable(false);
BorderLayout layout = new BorderLayout();
Container panel = new Container();
changeDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
JLabel textLabel = new JLabel("String Değiştirme İşlemi");
JLabel textLabel2 = new JLabel("Değiştiren (Yeni) Str");
JLabel textLabel3 = new JLabel("Değişen (Eski) Str");
JTextField changeInputField = new JTextField(10);
changeInputField.setMaximumSize(new Dimension(72, 36));
Icon changeIcon = new ImageIcon("changeIcon.png");
JButton changeButton = new JButton(changeIcon);
JTextField changingInputField = new JTextField(10);
changingInputField.setMaximumSize(new Dimension(90, 36));
if(!n.getSearchField().getText().isEmpty()){
String st = n.getSearchField().getText();
changingInputField.setText(st);
}
FlowLayout flow = new FlowLayout();
panel.setLayout(flow);
panel.add(textLabel2);
panel.add(changeInputField);
panel.add( Box.createHorizontalStrut( 5 ) );
panel.add(changeButton);
panel.add( Box.createHorizontalStrut( 5 ) );
panel.add(textLabel3);
panel.add(changingInputField);
changeDialog.add(textLabel,BorderLayout.NORTH);
changeDialog.add(panel);
changeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String textAreaStr = n.getTextArea().getText().toLowerCase();
String searchStr = changeInputField.getText().toLowerCase();
if(searchStr.isEmpty()){
JOptionPane.showMessageDialog(new JFrame(), "Değiştirme işlemi için bir Değiştiren (Yeni) String giriniz!");
}
else if(changingInputField.getText().isEmpty()){
JOptionPane.showMessageDialog(new JFrame(), "Değiştirme işlemi için bir Değişen (Eski) String giriniz!");
}
else if(textAreaStr.isEmpty()){
JOptionPane.showMessageDialog(new JFrame(), "Değiştirme işlemi için bir bir metin olması gerekmektedir!");
}
else{
String replaced = textAreaStr.replace(changingInputField.getText(), searchStr);
n.getTextArea().setText(replaced);
String t = changeInputField.getText();
changeInputField.setText(changingInputField.getText());
changingInputField.setText(t);
}
hatalariBoya(n);
}
});
changeDialog.setVisible(true);
}
});
}
//TextArea içinde bir string aramak istendiğinde searchButton'ı dinleyen metot. Yukarıdaki searchField'e yazılan string'i aramayı sağlıyor. Bulduğu kelimeleri
//kullanıcı rahat görebilsin diye boyuyor.
public void search(NotepadGui n){
n.getSearchButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//Önceki aramalarda kullanılan highlightlar temizlenir.
n.getTextArea().getHighlighter().removeAllHighlights();
//Arama kısmı boş olursa uyarı mesajı döndürür.
if(n.getSearchField().getText().isEmpty() ==true){
JOptionPane.showMessageDialog(new JFrame(), "Aramak için bir String giriniz!");
}
else{
String str = n.getSearchField().getText().toLowerCase();
//Kullanıcı olurda string ararken arama kısmında aranacak kelimenin sonuna boşluk koyarsa onları stringten temizlemeye yarıyor.
char emptyChar=' ';
while(str.charAt(str.length()-1)==emptyChar){
str = str.substring(0,str.length()-2);
}
String textAreaStr = n.getTextArea().getText().toLowerCase();
int offset = textAreaStr.indexOf(str);
int length = str.length();
while(offset != -1){
try {
n.setHighlightTag(n.getTextArea().getHighlighter().addHighlight(offset, offset + length, n.getPainter()));
offset = textAreaStr.indexOf(str, offset+1);
} catch (BadLocationException ble) {
System.out.println("Exception Occur!");
}
}
}
}
});
}
}
<file_sep>
package Notepad;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
//
public class TextAreaListener {
private NotepadGui n;
private String currentStr;
private CommandManager cmd;
public TextAreaListener(NotepadGui gui,CommandManager cmd){
n = gui;
currentStr = "";
this.cmd = cmd;
}
public void initiate(){
getN().getTextArea().addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent ke) {
getN().getStack().push((char)ke.getKeyChar());
//Kullanıcı yanlış kelimeyi düzeltirken kelimedeki highlight ı kaldırır. Görülmesi kolaylaşır
if((int)ke.getKeyChar()==8){
//System.out.println("backspace!!!!");
getN().getTextArea().getHighlighter().removeAllHighlights();
getN().getStack().clear();
for(int i=0;i<getN().getTextArea().getText().length();i++){
getN().getStack().push(getN().getTextArea().getText().charAt(i));
}
}
Operations op = new Operations();
op.hatalariBoya(getN());
//System.out.println(highlightTag);
if(getN().getHighlightTag()!= null){
getN().getTextArea().getHighlighter().removeHighlight(getN().getHighlightTag()); // Kullanıcı tekrar yazmaya başladığında arama yapılmış olan mavi highlightları siler
}
char ch = ke.getKeyChar();
setCurrentStr(getN().getTextArea().getText());
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//Burada TextCommand nesneleri oluşturulup cmd.Execute(); fonksiyonuna gönderiliyor. (gönderime işlemi 71. satırda)
TextCommand text = new TextCommand(getN());
text.setTextAreaStr(currentStr);
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
InputMap imap = getN().getTextArea().getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("SPACE"), "spaceAction");
ActionMap amap = getN().getTextArea().getActionMap();
amap.put("spaceAction", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
//System.out.println("Space Pressed: " + textArea.getText());
try {
op.errorCheck(getN());
} catch (IOException ex) {
System.out.println("Bilinmeyen bir hata meydana geldi.");
}
}
});
//Burada execute ediliyor. Böylece TextCommand'lar commandManager içindeki stack'te tutulabilecek.
getCmd().Execute(text, getN());
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
});
}
/**
* @return the n
*/
public NotepadGui getN() {
return n;
}
/**
* @param n the n to set
*/
public void setN(NotepadGui n) {
this.n = n;
}
/**
* @return the previousStr
*/
public String getCurrentStr() {
return currentStr;
}
/**
* @param previousStr the previousStr to set
*/
public void setCurrentStr(String previousStr) {
this.currentStr = previousStr;
}
/**
* @return the cmd
*/
public CommandManager getCmd() {
return cmd;
}
/**
* @param cmd the cmd to set
*/
public void setCmd(CommandManager cmd) {
this.cmd = cmd;
}
}<file_sep>
package Notepad;
import java.util.ArrayList;
import java.util.Stack;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class CommandManager {
private Stack<UndoableCommand> commandStack = new Stack();
private int _mevcut;
private NotepadGui gui;
public CommandManager(NotepadGui gui){
this.gui = gui;
_mevcut = 0;
}
void Execute(ICommand command,NotepadGui n){
//commandList.forEach(ICommand :: Perform);
commandStack.push((UndoableCommand)command);
//command.Perform(n);
//System.out.println("stack'e yüklendi, stackSize = "+commandStack.size());
//commandStack.push((UndoableCommand)command);
_mevcut++;
//System.out.println("Execute edildi + mevcut = "+_mevcut);
}
void Undo(NotepadGui n){
//System.out.println("Undo Edildi + mevcut = "+_mevcut);
if(_mevcut == 0){
JOptionPane.showMessageDialog(new JFrame(), "Daha fazla geri alma işlemi yapılamaz!");
return;
}
if(_mevcut>0){
//n.getTextArea().setText("");
//ICommand command = (ICommand) _commands.get(--_mevcut);
UndoableCommand comd= commandStack.pop();
//System.out.println("Stack size = "+commandStack.size());
comd.Undo();
}
_mevcut--;
}
}
<file_sep>
package Notepad;
public interface Container {
public MyIterator getIterator();
}
| 1387379e3a278d47fd588b42302b7095943e6d9d | [
"Markdown",
"Java"
] | 6 | Markdown | pinarcihangir/FullyFunctionalNotepadJava | 027eef6152c1c0de695421841137a8b7ad16c27a | 7079628574a9304e35b093f556880c10fbd99de5 |
refs/heads/master | <repo_name>cgrigs/FossilDates<file_sep>/code/Set_maker.sh
for i in {1..10}
do
python code/IntervalSampler.py
mkdir Data/$i
cp Data/accessory/* Data/$i
done<file_sep>/code/IntervalSampler.py
import pandas as pd
import numpy as np
from numpy import random
def taxon_sample(df, group_rank):
df = pd.read_csv(df)
df = df.dropna(axis=0)
samp = df.groupby(group_rank).apply(lambda x :x.iloc[random.choice(range(0,len(x)))])
return(samp)
def final_ages(tax_samp):
morph_temp = pd.read_csv("Data/taxa_template.tsv", sep='\t')
mol_temp = pd.read_csv("Data/Mol/mol_df.tsv", sep='\t')
morph_temp = morph_temp[['taxon', 'age']]
tax_samp = tax_samp[['SpecimenName', 'max_yr']]
tax_samp.columns = ['taxon', 'age']
stacked = pd.concat([morph_temp, mol_temp, tax_samp])
final_tip_age = stacked.drop_duplicates('taxon')
return(final_tip_age)
def foss_int(tax_samp):
morph_temp = pd.read_csv("Data/taxa_template.tsv", sep='\t')
morph_slim = morph_temp[['taxon', 'min_yr', 'max_yr']]
tax_samp = tax_samp[['SpecimenName', 'min_yr', 'max_yr']]
tax_samp.columns = ['taxon', 'min_yr', 'max_yr']
morph_slim = morph_slim[morph_slim.min_yr != 0.00]
stacked = pd.concat([tax_samp, morph_slim])
return(stacked)
if __name__ == '__main__':
tax_samp = taxon_sample('Data/higher_taxa.csv', 'SubFamily')
final_tip_age = final_ages(tax_samp)
final_tip_age.to_csv("Data/accessory/final_tip_age.tsv", sep = '\t', index=False)
stacked = foss_int(tax_samp)
stacked.to_csv("Data/accessory/foss_int.tsv", sep='\t', index =False)
| f1cda6a7d060c3df5830ade8df68dfdfabf409a2 | [
"Python",
"Shell"
] | 2 | Shell | cgrigs/FossilDates | 31ec3728a0409fad042142d0ddc08a3e744cb7b9 | 263a27bbd5a0e668ed89fa22c44ae5a0b7579a98 |
refs/heads/master | <repo_name>atlie15/Nerds<file_sep>/test/nerd.h
#ifndef NERD_H
#define NERD_H
class Nerd
{
public:
Nerd();
};
#endif // NERD_H
<file_sep>/test/nerd.cpp
#include "nerd.h"
Nerd::Nerd()
{
}
| 01005d300d4f516442f41fefec3a757e175edf31 | [
"C++"
] | 2 | C++ | atlie15/Nerds | 1b4c84697652cc72d0a3d8011390c351c5cfd262 | 60027d0c7798b305690ced3445fc7460e6562e89 |
refs/heads/master | <file_sep>/**
* Name: <NAME>
* ID : phn10
*/
import org.junit.*;
import static org.junit.Assert.*;
import java.util.Iterator;
import java.util.ListIterator;
/**
* A class that tests the methods of the DoubleLinkedList class
* @author <NAME>
*/
public class DoubleLinkedListTester {
/**
* Tests the addToFront method of DoubleLinkedList.
*/
@Test
public void testAddToFront() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
list.addToFront(3);
list.addToFront(2);
list.addToFront(1);
DLNode<Integer> head = list.getFront();
DLNode<Integer> tail = list.getBack();
assertEquals("Testing first node of list", new Integer(1), head.getElement());
assertEquals("Testing second node of list", new Integer(2), head.getNext().getElement());
assertEquals("Testing third node of list", new Integer(3), head.getNext().getNext().getElement());
assertEquals("Testing end of list", null, head.getNext().getNext().getNext());
assertEquals("Testing node at back of list", new Integer(3), tail.getElement());
assertEquals("Testing next to last node", new Integer(2), tail.getPrevious().getElement());
assertEquals("Testing third to last node", new Integer(1), tail.getPrevious().getPrevious().getElement());
assertEquals("Testing front of list", null, tail.getPrevious().getPrevious().getPrevious());
}
/**
* Tests the addToBack method of DoubleLinkedList.
*/
@Test
public void testAddToBack() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
list.addToBack(1);
list.addToBack(2);
list.addToBack(3);
DLNode<Integer> head = list.getFront();
DLNode<Integer> tail = list.getBack();
assertEquals("Testing last node of list", new Integer(3), tail.getElement());
assertEquals("Testing next to last node", new Integer(2), tail.getPrevious().getElement());
assertEquals("Testing third to last node", new Integer(1), tail.getPrevious().getPrevious().getElement());
assertEquals("Testing front of list", null, tail.getPrevious().getPrevious().getPrevious());
assertEquals("Testing node at front of list", new Integer(1), head.getElement());
assertEquals("Testing second node of list", new Integer(2), head.getNext().getElement());
assertEquals("Testing third node of list", new Integer(3), head.getNext().getNext().getElement());
assertEquals("Testing end of list", null, head.getNext().getNext().getNext());
}
/**
* Tests the removeFromFront method of DoubleLinkedList.
*/
@Test
public void testRemoveFromFront() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
list.addToFront(1);
list.addToFront(2);
list.addToFront(3);
assertEquals("Removing element of list", new Integer(3), list.removeFromFront());
assertEquals("Removing a second element", new Integer(2), list.removeFromFront());
assertEquals("Removing a third element", new Integer(1), list.removeFromFront());
assertEquals("Removed last element of list", true, list.isEmpty());
try {
list.removeFromFront();
fail("Removing from empty list did not throw an exception.");
}
catch (java.util.NoSuchElementException e) {
/* everything is good */
}
catch (Exception e) {
fail("Removing from empty list threw the wrong type of exception.");
}
list.addToBack(6);
list.addToBack(7);
assertEquals("Removing element added to back of list", new Integer(6), list.removeFromFront());
assertEquals("Removing second element added to back", new Integer(7), list.removeFromFront());
}
/**
* Tests the removeFromBack method of DoubleLinkedList.
*/
@Test
public void testRemoveFromBack() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
list.addToBack(5);
list.addToFront(4);
list.addToBack(6);
assertEquals("Removing element from back of list", new Integer(6), list.removeFromBack());
assertEquals("Removing second element from back of list", new Integer(5), list.removeFromBack());
assertEquals("Removing element from back that was added to front", new Integer(4), list.removeFromBack());
assertEquals("Removing last element of list", true, list.isEmpty());
try {
list.removeFromBack();
fail("Removing from empty list did not throw an exception.");
}
catch (java.util.NoSuchElementException e) {
/* everything is good */
}
catch (Exception e) {
fail("Removing from empty list threw the wrong type of exception.");
}
}
/**
* Tests the linked list iterator.
*/
@Test
public void testListIterator() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for (int i = 5; i > 0; i--)
list.addToFront(i);
/* checking that we get out what we put it */
int i = 1;
for (Integer x: list)
assertEquals("Testing value returned by iterator", new Integer(i++), x);
if (i != 6)
fail("The iterator did not run through all the elements of the list");
}
/**
* Tests the remove feature of the linked list iterator.
*/
@Test
public void testListIteratorRemove() {
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for (int i = 5; i > 0; i--)
list.addToFront(i);
/* testing removing the first element through the iterator */
Iterator<Integer> listIterator = list.iterator();
listIterator.next();
listIterator.remove();
/* the list should now be 2 through 5 */
int i = 2;
for (Integer x: list)
assertEquals("The iterator failed when removing the first element", new Integer(i++), x);
if (i != 6)
fail("The iterator failed when removing the first element");
/* testing removing element 3 */
listIterator = list.iterator();
listIterator.next();
listIterator.next();
listIterator.remove();
DLNode<Integer> head = list.getFront();
DLNode<Integer> tail = list.getBack();
assertEquals("Iterator failed to remove middle element", new Integer(2), head.getElement());
assertEquals("Iterator failed to remove middle element", new Integer(4), head.getNext().getElement());
assertEquals("Iterator failed to remove middle element", new Integer(5), head.getNext().getNext().getElement());
assertEquals("Iterator failed to remove middle element", tail.getNext(), head.getNext().getNext().getNext());
assertEquals("Iterator failed to remove middle element", new Integer(5), tail.getElement());
assertEquals("Iterator failed to remove middle element", new Integer(4), tail.getPrevious().getElement());
assertEquals("Iterator failed to remove middle element", new Integer(2), tail.getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to remove middle element", head.getPrevious(), tail.getPrevious().getPrevious().getPrevious());
/* testing removing the last element */
while (listIterator.hasNext())
listIterator.next();
listIterator.remove();
head = list.getFront();
tail = list.getBack();
assertEquals("Iterator failed to remove middle element", new Integer(2), head.getElement());
assertEquals("Iterator failed to remove middle element", new Integer(4), head.getNext().getElement());
assertEquals("Iterator failed to remove middle element", null, head.getNext().getNext());
assertEquals("Iterator failed to remove middle element", new Integer(4), tail.getElement());
assertEquals("Iterator failed to remove middle element", new Integer(2), tail.getPrevious().getElement());
assertEquals("Iterator failed to remove middle element", null, tail.getPrevious().getPrevious());
/* testing removing before calling next */
listIterator = list.iterator();
try {
listIterator.remove();
fail("Calling iterator's remove() before calling next() should throw an IllegalStateException");
}
catch (IllegalStateException e) {
// all is good
}
catch (Exception e) {
fail("The wrong exception thrown by the iterator remove() method.");
}
}
/*------------------------------------------------------*/
/* THIS IS THE PART I WORTE FOR THE TESTING THE PROJECT */
/*------------------------------------------------------*/
/* test equals() method of DoubleLinkedList*/
@Test
public void testEquals()
{
DoubleLinkedList<Integer> list1 = new DoubleLinkedList<Integer>();
DoubleLinkedList<Integer> list2 = new DoubleLinkedList<Integer>();
String l = new String("this is a string");
assertEquals("Test zero: there is no element in both list", list1.equals(list2), false);
list1.addToFront(1);
list2.addToFront(1);
assertEquals("Test one: there is one element in both list", list1.equals(list2), true);
/* test conflict types */
assertEquals("Test confilct types: DoubleLinkedList cannot be compared to String", list1.equals(l), false);
list1.addToFront(2);
list2.addToFront(2);
/* test many */
assertEquals("Test many: there are two element in both list", list1.equals(list2), true);
list1.addToFront(4);
list2.addToFront(4);
/* test many */
assertEquals("Test many: there are three element in both list", list1.equals(list2), true);
list2.addToBack(5);
/* test many */
assertEquals("Test many: two lists have different length", list1.equals(list2), false);
list1 = new DoubleLinkedList<Integer>();
list2 = new DoubleLinkedList<Integer>();
list1.addToFront(1);
list1.addToBack(2);
list1.addToBack(3);
list1.addToBack(4);
list2.addToFront(5);
list2.addToBack(2);
list2.addToBack(3);
list2.addToBack(4);
/* test first: the first elements in two list are different */
/* 1234 and 5234 */
assertEquals("Test first: the first elements in two list are different", list1.equals(list2), false);
list1 = new DoubleLinkedList<Integer>();
list2 = new DoubleLinkedList<Integer>();
list1.addToFront(1);
list1.addToBack(2);
list1.addToBack(3);
list1.addToBack(4);
list2.addToFront(1);
list2.addToBack(2);
list2.addToBack(5);
list2.addToBack(4);
/* the last elements in two list are different */
/* 1234 and 1254 */
assertEquals("Test middle: the middle elements in two list are different", list1.equals(list2), false);
list1 = new DoubleLinkedList<Integer>();
list2 = new DoubleLinkedList<Integer>();
list1.addToFront(1);
list1.addToBack(2);
list1.addToBack(3);
list1.addToBack(4);
list2.addToFront(1);
list2.addToBack(2);
list2.addToBack(5);
list2.addToBack(4);
/* the last elements in two list are different */
/* 1234 and 1235 */
assertEquals("Test last: the last elements in two list are different", list1.equals(list2), false);
}
/* test append() method of DoubleLinkedList */
@Test
public void testAppend()
{
DoubleLinkedList<Integer> list1 = new DoubleLinkedList<Integer>();
DoubleLinkedList<Integer> list2 = new DoubleLinkedList<Integer>();
DoubleLinkedList<Integer> list3 = new DoubleLinkedList<Integer>();
list1.addToFront(1); // add 1 to the front of list1
list2.addToFront(2); // add 2 to the front of list2
list1.append(list2); // append list2 to list1
list3.addToFront(1); // add 1 and 2 to list3
list3.addToBack(2);
assertEquals("Test many: there are more than one element in the list", list1.equals(list3), true);
}
/* test length() method of DoubleLinkedList */
@Test
public void testLength()
{
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
assertEquals("Test zero: there is none element in each list", list.length(), 0);
list.addToFront(1);
assertEquals("Test one: there is one element in each list", list.length(), 1);
list.addToFront(2);
list.addToFront(3);
assertEquals("Test many: there are many element in each list", list.length(), 3);
}
/* test two new features of the listIterator
* including: previous(), hasPrevious()*/
@Test
public void testNextandPreviousIterator()
{
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for (int i = 5; i > 0; i--)
list.addToFront(i);
ListIterator<Integer> it = list.iterator();
/* test next() and hasNext() method */
assertEquals("Test first element", it.hasNext(), true);
assertEquals("Test first element", (int)it.next(), 1);
assertEquals("Test middle element", it.hasNext(), true);
assertEquals("Test middle element", (int)it.next(), 2);
assertEquals("Test middle element", it.hasNext(), true);
assertEquals("Test middle element", (int)it.next(), 3);
assertEquals("Test middle element", it.hasNext(), true);
assertEquals("Test middle element", (int)it.next(), 4);
assertEquals("Test middle element", it.hasNext(), true);
assertEquals("Test last element", (int)it.next(), 5);
assertEquals("Test last element", it.hasNext(), false);
/*test previous() and hasPrevious() method */
assertEquals("Test last element", it.hasPrevious(), true);
assertEquals("Test last element", (int)it.previous(), 4);
assertEquals("Test middle element", it.hasPrevious(), true);
assertEquals("Test middle element", (int)it.previous(), 3);
assertEquals("Test middle element", it.hasPrevious(), true);
assertEquals("Test middle element", (int)it.previous(), 2);
assertEquals("Test middle element", it.hasPrevious(), true);
assertEquals("Test first element", (int)it.previous(), 1);
assertEquals("Test first element", it.hasPrevious(), false);
/* special condition: when the list has only two element */
list = new DoubleLinkedList<Integer>();
list.addToFront(1);
list.addToBack(2);
it = list.iterator();
assertEquals("Special condition: test first", new Integer(1), it.next());
assertEquals("Special condition: test last", new Integer(2), it.next());
assertEquals("Special condition: test last", false, it.hasNext());
assertEquals("Special condition: test first", new Integer(1), it.previous());
assertEquals("Special condition: test first", false, it.hasPrevious());
}
/* test the set() features of the listIterator */
@Test
public void testSetListIterator()
{
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for (int i = 5; i > 0; i--)
list.addToFront(i);
ListIterator<Integer> listIterator = list.iterator();
/* set the first element */
listIterator.next();
listIterator.set(6);
/* the list now should be 6 2 3 4 5 */
int i = 2;
assertEquals("The iterator failed when setting the first element", new Integer(6), list.getFront().getElement());
assertEquals("The iterator failed when setting the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when setting the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when setting the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when setting the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when setting the first element", false , listIterator.hasNext());
/* testing setting element 3 to 12 */
listIterator = list.iterator();
listIterator.next();
listIterator.next();
listIterator.next();
listIterator.set(12);
DLNode<Integer> head = list.getFront();
DLNode<Integer> tail = list.getBack();
/* the list now should be 6 2 12 4 5 */
assertEquals("Iterator failed to set middle element", new Integer(6), head.getElement());
assertEquals("Iterator failed to set middle element", new Integer(2), head.getNext().getElement());
assertEquals("Iterator failed to set middle element", new Integer(12), head.getNext().getNext().getElement());
assertEquals("Iterator failed to set middle element", new Integer(4), head.getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to set middle element", new Integer(5), head.getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to set middle element", null, head.getNext().getNext().getNext().getNext().getNext());
assertEquals("Iterator failed to set middle element", new Integer(5), tail.getElement());
assertEquals("Iterator failed to set middle element", new Integer(4), tail.getPrevious().getElement());
assertEquals("Iterator failed to set middle element", new Integer(12), tail.getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set middle element", new Integer(2), tail.getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set middle element", new Integer(6), tail.getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set middle element", null, tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious());
/* testing setting the last element */
while (listIterator.hasNext())
listIterator.next();
listIterator.set(33);
head = list.getFront();
tail = list.getBack();
/* the list now should be 6 2 12 4 33 */
assertEquals("Iterator failed to set last element", new Integer(6), head.getElement());
assertEquals("Iterator failed to set last element", new Integer(2), head.getNext().getElement());
assertEquals("Iterator failed to set last element", new Integer(12), head.getNext().getNext().getElement());
assertEquals("Iterator failed to set last element", new Integer(4), head.getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to set last element", new Integer(33), head.getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to set last element", null, head.getNext().getNext().getNext().getNext().getNext());
assertEquals("Iterator failed to set last element", new Integer(33), tail.getElement());
assertEquals("Iterator failed to set last element", new Integer(4), tail.getPrevious().getElement());
assertEquals("Iterator failed to set last element", new Integer(12), tail.getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set last element", new Integer(2), tail.getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set last element", new Integer(6), tail.getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to set last element", null, tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious());
/* testing setting before calling next() */
listIterator = list.iterator();
try {
listIterator.set(33);
fail("Calling iterator's set() before calling next() should throw an IllegalStateException");
}
catch (IllegalStateException e) {
// all is good
}
catch (Exception e) {
fail("The wrong exception thrown by the iterator remove() method.");
}
/* testing setting after calling add() or remove() */
listIterator = list.iterator();
try {
listIterator.next();
listIterator.add(10);
listIterator.remove();
listIterator.set(33);
fail("Calling iterator's set() after calling neither add() or remove() should throw an IllegalStateException");
}
catch (IllegalStateException e) {
// all is good
}
catch (Exception e) {
fail("The wrong exception thrown by the iterator remove() method.");
}
}
/* test the add() features of the listIterator */
@Test
public void testAddListIterator()
{
DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
for (int i = 5; i > 0; i--)
list.addToFront(i);
ListIterator<Integer> listIterator = list.iterator();
/* add the first element after calling next()*/
listIterator.next();
listIterator.add(6);
/* the list now should be 6 1 2 3 4 5 */
int i = 1;
listIterator = list.iterator();
assertEquals("The iterator failed when adding the first element", new Integer(6), listIterator.next());
assertEquals("The iterator failed when adding the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when adding the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when adding the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when adding the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when adding the first element", new Integer(i++), listIterator.next());
assertEquals("The iterator failed when adding the first element", false , listIterator.hasNext());
/* testing adding 12 after third element */
listIterator = list.iterator();
listIterator.next();
listIterator.next();
listIterator.next();
listIterator.add(12);
DLNode<Integer> head = list.getFront();
DLNode<Integer> tail = list.getBack();
/* the list now should be 6 1 2 12 3 4 5 */
assertEquals("Iterator failed to add middle element", new Integer(6), head.getElement());
assertEquals("Iterator failed to add middle element", new Integer(1), head.getNext().getElement());
assertEquals("Iterator failed to add middle element", new Integer(2), head.getNext().getNext().getElement());
assertEquals("Iterator failed to add middle element", new Integer(12), head.getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add middle element", new Integer(3), head.getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add middle element", new Integer(4), head.getNext().getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add middle element", new Integer(5), head.getNext().getNext().getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add middle element", null, head.getNext().getNext().getNext().getNext().getNext().getNext().getNext());
assertEquals("Iterator failed to add middle element", new Integer(5), tail.getElement());
assertEquals("Iterator failed to add middle element", new Integer(4), tail.getPrevious().getElement());
assertEquals("Iterator failed to add middle element", new Integer(3), tail.getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add middle element", new Integer(12), tail.getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add middle element", new Integer(2), tail.getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add middle element", new Integer(1), tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add middle element", new Integer(6), tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add middle element", null, tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious());
/* testing removing the last element */
while (listIterator.hasNext())
listIterator.next();
listIterator.add(21);
head = list.getFront();
tail = list.getBack();
/* the list now should be 6 1 2 12 3 4 5 21 */
assertEquals("Iterator failed to add last element", new Integer(6), head.getElement());
assertEquals("Iterator failed to add lsat element", new Integer(1), head.getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(2), head.getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(12), head.getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(3), head.getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(4), head.getNext().getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(5), head.getNext().getNext().getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", new Integer(21), head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getElement());
assertEquals("Iterator failed to add last element", null, head.getNext().getNext().getNext().getNext().getNext().getNext().getNext().getNext());
assertEquals("Iterator failed to add last element", new Integer(21), tail.getElement());
assertEquals("Iterator failed to add last element", new Integer(5), tail.getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(4), tail.getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(3), tail.getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(12), tail.getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(2), tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(1), tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", new Integer(6), tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getElement());
assertEquals("Iterator failed to add last element", null, tail.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious().getPrevious());
}
}<file_sep>/**
* This class represents the real number
* @author <NAME>
*/
public class RealN extends ComplexN
{
/**
* Constructor
* @param realNum the real number
*/
public RealN(double realNum)
{
super(realNum, 0);
}
}
<file_sep>/**
* Name: <NAME>
* ID : phn10
*/
import java.util.ListIterator;
/**
* A class represent a DNA array
*/
public class DNA extends DoubleLinkedList<DNA.Base>
{
/* enum contains four bases of DNA, A, C, G, T */
public enum Base
{
A, C, G, T;
}
/**
* return the string representation of the DNA array
* @return the string representation of the DNA array
*/
@Override
public String toString()
{
/* string builder */
StringBuilder str = new StringBuilder();
/* list iterator of the dna */
ListIterator list = this.iterator();
/* iterate through the list and add the char representation of the each element
* to the string */
for (Base b : this)
str.append((String.valueOf(b)));
String string = str.toString();
return string;
}
/**
* receive a string and convert that string to DNA array
* @parram s input string
* @return DNA list representation of the DNA array
*/
public static DNA string2DNA(String s)
{
DNA dna = new DNA();
/* create an warning message when the string is empty */
if (s.length() == 0)
throw new IllegalArgumentException("The String should not be empty");
try
{
/* iterate through array and add each element of the string to the dna */
for (char ch : s.toCharArray())
{
dna.addToBack(DNA.Base.valueOf(String.valueOf(ch)));
}
} catch (IllegalArgumentException e) {
System.err.println("Error: The DNA arrays should only contain Base character");
return null;
}
return dna;
}
/* splice two dna array into one
* @param dna the second dna
* @param numbases the number of merged element
*/
public void splice(DNA dna, int numbases)
{
int i = 0;
DLNode<DNA.Base> node = dna.getFront();
/* traverse through the dna array until either passed numbases nodes or the current node is null */
while (i < numbases && node != null)
{
i++;
node = node.getNext();
}
/* if the node is not null, append the current node to the last of this node */
if (node != null)
{
this.getBack().setNext(node);
node.setPrevious(this.getBack());
this.setBack(dna.getBack());
}
}
/**
* find the overlaps part between the first dna and the second dna
* @param dna1 the first dna
* @param dna2 the second dna
* @param n the number of match base
* @return true if two base overlap, false if not
*/
public static boolean overlaps(DNA dna1, DNA dna2, int n)
{
DLNode node1 = dna1.getBack();
DLNode node2 = dna2.getFront();
/* return false if the number of base is greater than either dnas length */
if (n > dna1.length() || n > dna2.length() || n == 0)
return false;
/* get the nth node from the back of the first dna */
for (int i = 0; i < n - 1; i++)
node1 = node1.getPrevious();
int j = 0;
/* traverse through the back of first dna and the head of second dna
* and compare the element in each corresponding position in each dna
*/
while (j < n - 1 && node1.getElement() == node2.getElement())
{
j++;
node1 = node1.getNext();
node2 = node2.getNext();
}
/* return false if the while loop cannot finish n - 1 steps, which means they are not overlaps */
if (node1 != null && node2 != null && node1.getElement() != node2.getElement())
return false;
/* else return true */
return true;
}
public static void main(String args[])
{
/* print out error if the user enter more or less than two string */
if (args.length != 2)
{
System.out.println("Error: You should enter two strings");
return;
}
try
{
DNA d1 = new DNA();
DNA d2 = new DNA();
int spliced12 = 0;
int spliced21 = 0;
d1 = DNA.string2DNA(args[0]);
d2 = DNA.string2DNA(args[1]);
int index = 1;
/* traverse through two dna and find the maximum number of overlap bases in two case
* the second dna is appended to the first dna
* the first dna is appended to the second dna
*/
while (index <= d1.length() && index <= d2.length())
{
if (overlaps(d1, d2, index))
spliced12 = index;
if (overlaps(d2, d1, index))
spliced21 = index;
index++;
}
/* there is no overlap */
if (spliced12 == 0 && spliced21 == 0)
{
System.out.println("");
}
/* splice the second onto the first */
else if (spliced12 > spliced21)
{
d1.splice(d2, spliced12);
System.out.println(d1);
}
/* splice the fisrt onto the second */
else
{
d2.splice(d1, spliced21);
System.out.println(d2);
}
} catch (Exception e) {}
}
} <file_sep>/**
* Name: <NAME>
* ID : phn10
*/
import java.util.Collection;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
/**
* A doubly linked linked list.
*/
public class DoubleLinkedList<T> implements Iterable<T> {
/** a reference to the first node of the double linked list */
private DLNode<T> front;
/** a reference to the last node of a double linked list */
private DLNode<T> back;
/** Create an empty double linked list. */
public DoubleLinkedList() {
front = back = null;
}
/**
* Returns true if the list is empty.
* @return true if the list has no nodes
*/
public boolean isEmpty() {
return (getFront() == null);
}
/**
* Returns the reference to the first node of the linked list.
* @return the first node of the linked list
*/
protected DLNode<T> getFront() {
return front;
}
/**
* Sets the first node of the linked list.
* @param node the node that will be the head of the linked list.
*/
protected void setFront(DLNode<T> node) {
front = node;
}
/**
* Returns the reference to the last node of the linked list.
* @return the last node of the linked list
*/
protected DLNode<T> getBack() {
return back;
}
/**
* Sets the last node of the linked list.
* @param node the node that will be the last node of the linked list
*/
protected void setBack(DLNode<T> node) {
back = node;
}
/*----------------------------------------*/
/* METHODS TO BE ADDED DURING LAB SESSION */
/*----------------------------------------*/
/**
* Add an element to the head of the linked list.
* @param element the element to add to the front of the linked list
*/
public void addToFront(T element) {
if (this.isEmpty())
{
DLNode<T> newNode = new DLNode<T>(element, null, null);
this.setFront(newNode);
this.setBack(newNode);
}
else
{
DLNode<T> newNode = new DLNode<T>(element, null, this.getFront());
this.getFront().setPrevious(newNode);
this.setFront(newNode);
}
}
/**
* Add an element to the tail of the linked list.
* @param element the element to add to the tail of the linked list
*/
public void addToBack(T element) {
if (this.isEmpty())
{
DLNode<T> newNode = new DLNode<T>(element, null, null);
this.setFront(newNode);
this.setBack(newNode);
}
else
{
DLNode<T> newNode = new DLNode<T>(element, this.getBack(), null);
this.getBack().setNext(newNode);
this.setBack(newNode);
}
}
/**
* Remove and return the element at the front of the linked list.
* @return the element that was at the front of the linked list
* @throws NoSuchElementException if attempting to remove from an empty list
*/
public T removeFromFront() {
if (this.isEmpty())
{
throw new NoSuchElementException();
}
else
{
T element = this.getFront().getElement();
this.setFront(this.getFront().getNext());
return element;
}
}
/**
* Remove and return the element at the back of the linked list.
* @return the element that was at the back of the linked list
* @throws NoSuchElementException if attempting to remove from an empty list
*/
public T removeFromBack() {
if (this.isEmpty())
{
throw new NoSuchElementException();
}
else
{
T element = this.getBack().getElement();
this.setBack(this.getBack().getPrevious());
if (this.getBack() == null)
this.setFront(null);
return element;
}
}
/**
* Compare the two double linked list
* @param obj the compared linked list
* @return true if two list are equal, false if not
*/
@Override
public boolean equals(Object obj)
{
/* if obj is DoubleLinkedList */
if (obj instanceof DoubleLinkedList)
{
/* change obj current type to DoubleLinkedList */
DoubleLinkedList list2 = (DoubleLinkedList)obj;
/* if either list is empty, return false */
if (this.isEmpty() || list2.isEmpty())
return false;
Iterator it1 = this.iterator();
Iterator it2 = list2.iterator();
/* iterate through list1 and list2
* and compare the element at the same position of two list */
while(it1.hasNext() && it2.hasNext())
{
if (it1.next() != it2.next())
return false;
}
/* if one of the list have element, return false */
if (it1.hasNext() || it2.hasNext())
return false;
else
return true;
}
else
return false;
}
/**
* append the second list to the first list which calls this method
* @param list the second list
* @exception NoSuchElementException when either list is empty
*/
public void append(DoubleLinkedList<T> list)
{
try
{
this.getBack().setNext(list.getFront());
list.getFront().setPrevious(this.getBack());
this.setBack(list.getBack());
} catch (NoSuchElementException e)
{ System.out.println("Either list should not be empty"); }
}
/**
* get number of nodes in this list
* @return the number of nodes in this list
*/
public int length()
{
int i = 0;
DLNode<T> nodePtr = this.getFront();
while (nodePtr != null)
{
i++;
nodePtr = nodePtr.getNext();
}
return i;
}
/**
* Returns an interator for the linked list that starts at the head of the list and runs to the tail.
* @return the iterator that runs through the list from the head to the tail
*/
@Override
public ListIterator<T> iterator() {
return new ListIterator<T>() {
/* create a new node point to the first node of this list */
private DLNode<T> nodePtr = DoubleLinkedList.this.getFront();
/* user can only call set() and remove() when setAvailable is true */
private boolean setAvailable = false;
/* isBack determines if the nodePtr points to the end of the list */
private boolean isBack = false;
/**
* determine the possibility of moving next
* @return true if can move next, false if not
*/
@Override
public boolean hasNext()
{
return !isBack;
}
/**
* return the element of the next node
* @return the element of the next node
* @exception NoSuchElementException if the pointer point to the end of the list
*/
@Override
public T next()
{
if (!this.hasNext())
throw new NoSuchElementException();
/* if the node pointer points to the back node */
if (nodePtr == DoubleLinkedList.this.getBack())
isBack = true;
setAvailable = true;
// return the element of nodePtr and move nodePtr to the next node
T element = nodePtr.getElement();
if (!isBack)
nodePtr = nodePtr.getNext();
return element;
}
/**
* determine the possibility of moving backward
* @return true if can move back, false if not
*/
@Override
public boolean hasPrevious()
{
if (isBack && nodePtr.getPrevious() != null)
return true;
if (nodePtr.getPrevious() == null || nodePtr.getPrevious().getPrevious() == null)
return false;
else
return true;
}
/**
* return the element of the previous node
* @return the element of the previous node
* @exception NoSuchElementException if the pointer points to the front of the list
*/
@Override
public T previous()
{
if (!this.hasPrevious())
throw new NoSuchElementException();
setAvailable = true;
// return the element of the previous two node of nodePtr and move nodePtr to previous node
T element;
if (isBack)
element = nodePtr.getPrevious().getElement();
else
{
element = nodePtr.getPrevious().getPrevious().getElement();
nodePtr = nodePtr.getPrevious();
}
/* the nodePtr doesn't point to the last node anymore */
isBack = false;
return element;
}
/**
* add one new element to the list, the node contains this element must follow the API rules
* @param element the element user want to add
*/
@Override
public void add(T element)
{
setAvailable = false;
DLNode<T> node;
// case 1: add before the list
if (!this.hasPrevious() || DoubleLinkedList.this.isEmpty())
DoubleLinkedList.this.addToFront(element);
// case 2: add at the end of the list
else if (!this.hasNext())
DoubleLinkedList.this.addToBack(element);
// case 3: add to the middle
else
{
node = new DLNode<T>(element, nodePtr.getPrevious(), nodePtr);
}
}
/**
* replace the element of the current node (the node immediately before nodePtr) by new element
* @param element the element user want to set
*/
@Override
public void set(T element)
{
if (!setAvailable)
throw new IllegalStateException();
else
{
if (nodePtr.getNext() == null)
nodePtr.setElement(element);
else
nodePtr.getPrevious().setElement(element);
}
}
@Override
public int nextIndex()
{
throw new UnsupportedOperationException();
}
@Override
public int previousIndex()
{
throw new UnsupportedOperationException();
}
/**
* remove the node immediately before the nodePtr
* @exception IllegalStateException if calling remove() before calling next()
*/
@Override
public void remove()
{
setAvailable = false;
/* if calling remove() before next() */
if (nodePtr == DoubleLinkedList.this.getFront())
{
throw new IllegalStateException();
}
/* we have to divide into 3 cases:
* case 1: remove the first element
* case 2: remove the last eleemnt
* case 3: remove the middle element
*/
/* case 1: remove the first element */
if (nodePtr == DoubleLinkedList.this.getFront().getNext())
{
DoubleLinkedList.this.setFront(DoubleLinkedList.this.getFront().getNext());
DoubleLinkedList.this.getFront().setPrevious(null);
}
/* case 2: remove the last element */
else if (nodePtr == DoubleLinkedList.this.getBack())
{
DoubleLinkedList.this.setBack(DoubleLinkedList.this.getBack().getPrevious());
DoubleLinkedList.this.getBack().setNext(null);
}
/* removing middle element */
else
{
nodePtr.getPrevious().getPrevious().setNext(nodePtr);
nodePtr.setPrevious(nodePtr.getPrevious().getPrevious());
}
}
};
}
}<file_sep>Programming Project 1
Due Friday, February 19 at 11:59pm
IMPORTANT: Read the Do's and Dont's in the Course Honor Policy found on blackboard.
I. Overview
The theme of this assignment is to write code to create an account for a student at a university. The purpose is to give you practice writing classes, fields, methods, conditional statements, and constructors. You will also be introduced to polymorphism.
II. Code Readability (20% of your project grade)
Once upon a time, getting a program to work was the only goal of programming. That was before computers took over the world. Now, with highly complex software running much of our lives, the industry has learned that computer code is a written document that must be able to communicate to other humans what the code is doing. If the program is too hard for a human to quickly understand, the company does not want it.
Most companies enforce readable code by having very strict rules about how the program should look. This class will do the same, but will not be quite as strict so you can have some freedom for developing your own style.
To receive the full readability marks, your code must follow the following guideline:
All variables (fields, parameters, local variables) must be given appropriate and descriptive names.
All variable and method names must start with a lowercase letter. All class names must start with an uppercase letter.
The class body should be organized so that all the fields are at the top of the file, the constructors are next, and then the rest of the methods.
There should not be two statements on the same line.
All code must be properly indented (see page 689 of the Lewis book for an example of good style). The amount of indentation is up to you, but it should be at least 2 spaces, and it must be used consistently throughout the code.
You must be consistent in your use of {, }. The closing } must be on its own line and indented the same amount as the line containing the opening {.
There must be an empty line between each method.
There must be a space separating each operator from its operands as well as a space after each comma.
There must be a comment at the top of the file that includes both your name and a description of what the class represents.
There must be a comment directly above each method that, in one or two lines, states what task the method is doing, not how it is doing it. Do not directly copy the homework instructions.
There must be a comment directly above each field that, in one line, states what the field is storing.
There must be a comment either above or to the right of each non-field variable indicating what the variable is storing. Any comments placed to the right should be aligned so they start on the same column.
III. Program Testing Document (20% of your project grade)
Once upon a time, companies thought errors in code were only a minor inconvenience. That was before software glitches started killing people and destroying companies. Now, standard practice is that all code must be thoroughly verified before a company is willing to release it. At a large number of firms, programmers are required to first design the test cases the program must pass and then start writing the code. We will not be that strict in this class, but you will need to test your code.
To receive full testing marks, you must write a testing report that shows that you thoroughly tested every method of the program. The report should be a short English description for each test (what you are testing and what the expected result of the test is) followd by the actual result of the test. If you are using DrJava, you can enter the test into the interactions pane and then copy and paste the test code plus the result to your report. If you fail to complete the program, your report should indicate how you would go about testing the incomplete methods.
Your grade on the testing report is how thoroughly you test your code, not how correctly your code runs. If your code is not 100% correct then your report should show an incorrect result to some test. Testing methods that do not have conditional statements should be pretty straightforward, but you need to put thought into testing methods with conditional statements so that each branch of the if-statement is tested.
Hint 1: You can test multiple methods with one test. For example, you can test each setter/getter method pair together or you can test constructors and getter methods together.
Hint 2: Do not put off testing to the end! Test each method after you complete it. Many methods depend on other methods. Delaying testing could mean cascading errors that cause your whole project to collapse. Since you need to test anyway, copy the tests you do into a document, and you are most of the way to completing your report.
If you are not using DrJava, you are allowed (but not required) create a separate class that tests your program. You must still write a testing report that documents the tests you do in this class. Do not place testing code into a main method of the classes below. That is not the purpose of a main method.
IV. Java Programming (60% of your grade)
Guidelines for the program:
All the listed methods must be public.
You will need to create several instance fields to store data, and every field must be private.
All fields must be initialized to an appropriate value. They can be initialized either as part if the field declaration or in the constructor. Even if you feel that the default value provided by Java is appropriate, you still must give an explicit initialization.
Any method whose name begins with set should only assign a value to an appropriately named field. The method should do no other processing. Any processing described in a set method description below is for information only. That actual processing will be done by other methods.
Any method whose name begins with get should only return the appropriate value. No other processing should occur in these methods.
Your class must include only the methods listed. You may not write any other methods.
The behavior of your methods must match the descriptions below.
You should not write any loops in your program (though loops are allowed in the testing code).
The program: You will create the following four classes. The classes are listed in order of challenge from more straightforward to more challenging.
Account
The Account represents a general purpose account that records the amount of money an individual owes. The Account class will need instance fields to keep track of an account number, the current balance for the account, and a balance limit for the account. The class will have the following methods:
getAccountNumber
Takes no input and returns a String. Returns the account number of the account. (The account number will never change.)
getBalance
Takes no input and returns a double. Returns the current balance of the account.
charge
Takes a single double value as input and returns nothing. The balance is increased by the input amount.
credit
Takes a single double value as input and returns nothing. The balance is decreased by the input amount.
setBalanceLimit
Takes a single int value as input and returns nothing. Changes the balance limit to be the input value.
getBalanceLimit
Takes no input and returns an int. Returns the balance limit of the account.
The Account class will have two constructors:
The first constructor takes a single String input that is the account number.
The second constructor takes two inputs, a String that is the account number and an int that is the balance limit.
LibraryAccount
A LibraryAccount is the financial record of a library patron. It records whether the patron has any overdue material and how much money, in fines, has been assessed to the patron. The LibraryAccount class should extend the Account class. Besides including all the methods that Account has, the LibraryAccount will have the following additional methods:
setBookFine
Takes a single double value as input and returns nothing. The input value will be the size of the fine that is assessed each day a book is overdue.
getBookFine
Takes no input and returns a double. Returns the amount that will be fined for each day a book is overdue.
setReserveFine
Takes a single double value as input and returns nothing. The input value will be the size of the fine that is assessed each day a reserved item is overdue.
getReserveFine
Takes no input and returns a double. Returns the amount that will be fined for each day a reserved item is overdue.
incrementOverdueBooks
Takes no input and returns nothing. Increases by one the number of overdue books on the account.
decrementOverdueBooks
Takes no input and returns nothing. Decreases by one the number of overdue books on the account. Does not decrease the count below zero.
getNumberOverdueBooks
Takes no input and returns an int. Returns the number of overdue books on the account.
incrementOverdueReserve
Takes no input and returns nothing. Increases by one the number of overdue reserved items on the account.
decrementOverdueReserve
Takes no input and returns nothing. Decreases by one the number of overdue reserved items on the account. Does not decrease the count below zero.
getNumberOverdueReserve
Takes no input and returns an int. Returns the number of overdue reserved items on the account.
canBorrow
Takes no input and returns a boolean. Returns true if the account's balance is equal or less than the account's balance limit. Returns false otherwise.
endOfDay
Takes no input and returns nothing. Increases the account's balance by the product of the number of overdue books and the book fine, and increases the account's balance by the product of the number of overdue reserved items and the reserved items fine.
The LibraryAccount should have two constructors.
the first constructor takes a single String input that is the account number.
the second constructor takes four inputs: a String that is the account number, an int that is the balance limit, a double that is the book fine, and a double that is the reserved items fine.
CreditAccount
The CreditAccount class represents a situation where a customer can borrow money. The money is to be repaid at the end of the month, but if it is not repaid, an interest penalty is assessed. The CreditAccount class should extend the Account class. Besides including all the methods that Account has, the CreditAccount class will have the following additional methods:
setInterestRate
Takes a single double as input and returns nothing. Changes the interest rate for the account to the input value.
getInterestRate
Takes no input and returns a double. Returns the interest rate for the account.
getMonthlyPayment
Takes no input and returns a double. Returns the monthly payment amount. The montly payment is the amount that must be paid this month to avoid receiving an interest charge on the account balance. The monthly payment is different from the balance.
getAmountPaidThisMonth
Takes no input and returns a double. Returns the amount that has been credited to the account this month.
endOfMonth
Takes no input and returns nothing. First, the method should see if interest must be charged. If the amount paid this month is less than the monthly payment, the account's balance is increased by product of the interest rate and the balance, divided by 12.
 After checking for an interst charge, the method should reset the account by setting the monthly payment to be equal to the balance and setting the amount paid this month to zero.
Besides these methods, the CreditAccount class needs a different behavior for the credit method from that of the Account class.
The credit method in CreditAccount must increase the amount paid this month and decrease the account balance by the input value.
The CreditAccount should have a single constructor that takes 2 inputs: a String that is the account number and a double that is the interest rate.
StudentAccount
The StudentAccount class represents the financial accounts of a student. A student's account is divided into three parts: the amount they owe for tuition, the amount they owe for any dining charges, and the amount owed to the library for overdue items. the StudentAccount class should extend the Account class. Besudes incuding all the methods that Account has, the StudentAccount class will have the following additional methods:
setName
Takes a single input that is a String value and returns nothing. Changes the account owner's name to the input value.
getName
Takes no input and returns a String value. Returns the account owner's name.
setAddress
Takes a single input that is a String value and returns nothing. Changes the account owner's address to the input value.
getAddress
Takes no input and returns a String value. Returns the account owner's address.
setLibraryAccount
Takes a single input that is a LibraryAccount value and returns nothing. Changes the library account associated with this account to the input value. There does not have to be a library account associated with this account so the input value may be null.
getLibraryAccount
Takes no input and returns a LibraryAccount value. Returns the library account associated with this account.
setTuitionAccount
Takes a single input that is a CreditAccount value and returns nothing. Changes the tuition account associated with this account to the input value. There does not have to be a tuition account associated with this account so the input value may be null.
getTuitionAccount
Takes no input and returns a CreditAccount value. Returns the tuition account associated with this account.
setDiningAccount
Takes a single input that is a CreditAccount value and returns nothing. Changes the dining account associated with this account to the input value. There does not have to be a dining account associated with this account so the input value may be null.
getDiningAccount
Takes no input and returns a CreditAccount value. Returns the dining account associated with this account.
Besides these methods, the StudentAccount class needs to a different behavior for the following methods of Account:
getBalance: the getBalance method of StudentAccount should sum the balances of the library account, tuition account, and dining account that are associated with this account (if those accounts exist). The method should then subtract the account's refund amount from this sum and return that value.
charge: the charge method of StudentAccount should first subtract the input amount by the accounts's refund amount. If this difference is positive and the tuition account exists, the tuition account's balance should be increased by the difference. Otherwise, the account's refund amount should be set to the negation of this difference.
credit: the credit method of StudentAccount processes a payment to the student account, and the payment should be used to decrease the balances of the associated accounts in the following order: tuition, dining, library (if they exist). That is, you first apply the payment to reduce the tuition account balance. If there is any money left after reducing the tuition account, you reduce the dining account balance next and then the library account balance. If after reducing each existing account there is money left over, it should be added to the student account's refund amount. The total amount you apply to the associated accounts' balances should not exceed the input to this method.
 For the tuition and dining accounts, the account's balance should only be decreased until the account's amount paid this month equals the monthly payment.
 For the library account, the account's balance should not be reduced below zero.
In addition, the StudentAccount should have a single constructor that takes two String values as input. The first is the account number and the second is the account owner's name.
V. Submitting Your Project
Submit the .java files (not the .class files or the .java~ files) for each of your four classes plus the testing report on blackboard.
<file_sep>public class Account
{
private String account; // store account number of the account
private double balance; // store the account's balance
private int limit; // store the account balance limit
// first constructor, receive a String
// set the account number field
public Account(String account)
{
this.account = account;
}
// second constructor, receive a String and a integer
// set the account number and balance's limit
public Account(String account, int limit)
{
this.account = account;
this.limit = limit;
}
// return the account number
public String getAccountNumber()
{
return account;
}
// return the account balance
public double getBalance()
{
return balance;
}
// increase the account balance by the charge value
public void charge(double charge)
{
this.balance += charge;
}
// subtract the account balance by the credit value
public void credit(double credit)
{
this.balance -= credit;
}
// set the account balance limit
public void setBalanceLimit(int limit)
{
this.limit = limit;
}
// return the account balance limit
public int getBalanceLimit()
{
return limit;
}
}
<file_sep>/**
* Name: <NAME>
* ID : phn10
*/
import org.junit.*;
import static org.junit.Assert.*;
import java.util.Iterator;
import java.util.ListIterator;
import java.io.*;
/**
* A class that tests the methods of the DNA class
* @author <NAME>
*/
public class DNATester
{
/**
* test the toString method in DNA class
*/
@Test
public void testToString()
{
DNA dna = new DNA();
/* test zero */
try
{
assertEquals("Test zero: no element on the dna strand", dna.toString(), "");
} catch (Exception e)
{ /* everythings is fine */ }
dna.addToFront(DNA.Base.A);
/* test one */
assertEquals("Test one: test toString failed when there is one element on the dna strand", dna.toString(), "A");
dna.addToBack(DNA.Base.C);
dna.addToBack(DNA.Base.C);
dna.addToBack(DNA.Base.T);
dna.addToBack(DNA.Base.A);
dna.addToBack(DNA.Base.G);
/* test many */
assertEquals("Test many: test toString failed when there are more than one element on the dna strand", dna.toString(), "ACCTAG");
}
/**
* test the string2DNA method in DNA class
*/
@Test
public void testString2DNA()
{
DNA dna1 = new DNA();
DNA dna2 = new DNA();
dna1.addToFront(DNA.Base.A);
dna2 = DNA.string2DNA("A");
/* test one */
assertEquals("Test one: test string2DNA failed when there is one element on the dna strand", dna1.equals(dna2), true);
dna1.addToBack(DNA.Base.C);
dna1.addToBack(DNA.Base.G);
dna1.addToBack(DNA.Base.A);
dna1.addToBack(DNA.Base.T);
dna2 = DNA.string2DNA("ACGAT");
/* test many */
assertEquals("Test many: test string2DNA failed when there are more than one element on the dna strand", dna1.equals(dna2), true);
}
/**
* test the splice method in DNA class
*/
@Test
public void testSplice()
{
DNA dna1 = new DNA();
DNA dna2 = new DNA();
dna1.addToFront(DNA.Base.A);
dna2.addToFront(DNA.Base.C);
dna2.addToBack(DNA.Base.G);
dna2.addToBack(DNA.Base.T);
dna1.splice(dna2, 0);
/* test zero
* cut out zero element from the second dna
* the first dna should be ACGT
*/
assertEquals("Test zero: test splice failed to splice zero element from the second dna strand", dna1, DNA.string2DNA("ACGT"));
dna1 = new DNA();
dna2 = new DNA();
dna1.addToFront(DNA.Base.A);
dna2.addToFront(DNA.Base.C);
dna2.addToBack(DNA.Base.G);
dna2.addToBack(DNA.Base.T);
dna1.splice(dna2, 1);
/* test first
* cut out first element from the second dna
* the first dna should be AGT
*/
assertEquals("Test first: test splice failed to splice fisrt element from the second dna strand", dna1, DNA.string2DNA("AGT"));
dna1 = new DNA();
dna2 = new DNA();
dna1.addToFront(DNA.Base.A);
dna2.addToFront(DNA.Base.C);
dna2.addToBack(DNA.Base.G);
dna2.addToBack(DNA.Base.T);
dna1.splice(dna2, 2);
/* test middle
* cut out second element from the second dna
* the first dna should be AT
*/
assertEquals("Test middle: test splice failed to splice middle element from the second dna strand", dna1, DNA.string2DNA("AT"));
dna1 = new DNA();
dna2 = new DNA();
dna1.addToFront(DNA.Base.A);
dna2.addToFront(DNA.Base.C);
dna2.addToBack(DNA.Base.G);
dna2.addToBack(DNA.Base.T);
dna1.splice(dna2, 3);
/* test middle
* cut out last element from the second dna
* the first dna should be A
*/
assertEquals("Test last: test splice failed to splice last element from the second dna strand", dna1, DNA.string2DNA("A"));
}
/**
* test the overlaps method in DNA class
*/
@Test
public void testOverLaps()
{
DNA dna1 = new DNA();
DNA dna2 = new DNA();
dna1 = DNA.string2DNA("AAAAA");
dna2 = DNA.string2DNA("AAAAA");
/* test zero */
assertEquals("Test zero", DNA.overlaps(dna1, dna2, 0), false);
/*test first */
assertEquals("Test first: test overlaps failed when the cursor points to the first element", DNA.overlaps(dna1, dna2, 1), true);
/*test middle */
assertEquals("Test middle: test overlaps failed when the cursor points to the middle element", DNA.overlaps(dna1, dna2, 3), true);
/*test last */
assertEquals("Test first: test overlaps failed when the cursor points to the first element", DNA.overlaps(dna1, dna2, 5), true);
}
/**
* test main method in DNA class
*/
@Test
public void testMain()
{
DNA dna1 = new DNA();
DNA dna2 = new DNA();
/* test zero
* two strands do not overlap
* two strands: AAAAA and GGGG, there is no overlaps
* expcect the main method printout nothing
*/
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
DNA.main(new String[] {"AAAAA", "GGGG"});
assertEquals("Test first: the main method failed to splice when only first element overlaps", outContent.toString(), "" + "\n");
System.setOut(null); // clear setOut
/* test first
* only the first element in the second dna strand overlaps the first dna strand
* two strands: AGGTCT and TAAAAC, the overlaps part is T
* expcect the main method printout AGGTCTAAAC
*/
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
DNA.main(new String[] {"AGGTCT", "TAAAAC"});
assertEquals("Test first: the main method failed to splice when only first element overlaps", outContent.toString(), "AGGTCTAAAAC" + "\n");
System.setOut(null); // clear setOut
/* test middle
* the second dna overlaps half of the first dna strand
* two strands: CGCTCACCTAT and ATAATCGCTC, the overlap part is AT and CGCTC,
* but since CGCT is bigger than AT, expcect the main method printout AGGTCTAAAC
*/
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
DNA.main(new String[] {"CGCTCACCTAT", "ATAATCGCTC"});
assertEquals("Test middle: the main method failed to splice at middle element", outContent.toString(), "ATAATCGCTCACCTAT" + "\n");
System.setOut(null);
/* test last
* the first dna overlaps all of the second dna strand
* two strands: AAAAAT and AAAA, the overlap part is AAAA
* expcect the main method printout AAAAAT
*/
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
DNA.main(new String[] {"AAAAAT", "AAAA"});
assertEquals("Test last: the main method failed to splice to splice at last element", outContent.toString(), "AAAAAT" + "\n");
System.setOut(null);
}
} | 928fcf270bd9398034971a49eb67d89af2e587e9 | [
"Java",
"Text"
] | 7 | Java | phn10/Java | 19423a9f454b74ba9bc8e8241502cfbaf0daa203 | dcf3fd80efa82bf7ce19d179691ba176ebd83162 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CsvParser.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public int ColumnNumber { get; }
public ColumnAttribute(int columnNumber)
{
ColumnNumber = columnNumber;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CsvParser.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ExpectedDataTypeAttribute : Attribute
{
public Type FieldType { get; }
public ExpectedDataTypeAttribute(Type type)
{
FieldType = type;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using CsvParser.Attributes;
using FluentAssertions;
using NUnit.Framework;
namespace CsvParser.Tests
{
public class FileLoadTests
{
private FileLoad _fileLoad;
[SetUp]
public void SetUp()
{
}
[Test]
public void ShouldReturnDataObject()
{
var data = "1,2,3,4,5,6";
var dataItem = data.Split(',');
var dataObject = FileLoad.ConvertLineToDataObject(dataItem);
dataObject.Column1.Should().Contain("1");
dataObject.Column2.Should().Contain("2");
dataObject.Column3.Should().Contain("3");
dataObject.Column4.Should().Contain("4");
dataObject.Column5.Should().Contain("5");
dataObject.Column6.Should().Contain("6");
}
private static void UpdateTestDatabase(LoadedFile currentFile)
{
// do nothing
}
[TestCase("1,2,3,4,5,6,7")]
[TestCase("1,2,3,4")]
public void IncorrectNumberOfFieldsShouldCreateException(string data)
{
var dataArray = data.Split(',');
LoadedFile loadedFile = new LoadedFile
{
ValidRows = new List<DataObject>(),
Exceptions = new List<ExceptionMessages>(),
InvalidRows = new List<string>()
};
FileLoad.ValidateIncorrectNumberOfColumns(loadedFile, dataArray,6,1,data,5);
loadedFile.Exceptions.Should().HaveCount(1);
}
[Test]
public void ValidLineShouldMapToValidRows()
{
LoadedFile loadedFile = new LoadedFile();
loadedFile.ValidRows = new List<DataObject>();
DataObject validDataObject = new DataObject
{
Column1 = "Col1",
Column2 = "Col2",
Column3 = "Col3",
Column4 = "Col4",
Column5 = "Col5",
Column6 = "Col6",
};
FileLoad.AddValidRow(loadedFile, validDataObject);
loadedFile.ValidRows.Should().HaveCount(1);
}
[Test]
public void InvalidLineShouldNotMapToValidRows()
{
LoadedFile loadedFile = new LoadedFile();
loadedFile.ValidRows = new List<DataObject>();
DataObject validDataObject = new DataObject
{
Column1 = "",
Column2 = "Col2",
Column3 = "Col3",
Column4 = "Col4",
Column5 = "Col5",
Column6 = "Col6",
};
FileLoad.AddValidRow(loadedFile, validDataObject);
loadedFile.ValidRows.Should().HaveCount(0);
}
[TestCase(typeof(String),"test",5)]
[TestCase(typeof(Guid), "e5253a80-1c1a-4879-891a-ec138c5a994c", null)]
[TestCase(typeof(DateTime), "10/09/2018", null)]
[TestCase(typeof(Double), "10.00", null)]
[TestCase(typeof(Int32), "10", null)]
public void ShouldReturnTrueForValidFields(Type expectedType, string fieldValue,
int? fieldLength)
{
ExpectedDataTypeAttribute expected = new ExpectedDataTypeAttribute(expectedType);
if (fieldLength == null)
{
fieldLength = 0;
}
FixedLengthAttribute expectedLength = new FixedLengthAttribute((int)fieldLength);
FileLoad.ValidField(expected, fieldValue, expectedLength).Should().BeTrue();
}
[TestCase(typeof(String), "badString", 5)]
[TestCase(typeof(Guid), "badGuid", null)]
[TestCase(typeof(DateTime), "badDate", null)]
[TestCase(typeof(Double), "badDouble", null)]
[TestCase(typeof(Int32), "badInt", null)]
public void ShouldReturnFalseForInvalidFields(Type expectedType, string fieldValue,
int? fieldLength)
{
ExpectedDataTypeAttribute expected = new ExpectedDataTypeAttribute(expectedType);
if (fieldLength == null)
{
fieldLength = 0;
}
FixedLengthAttribute expectedLength = new FixedLengthAttribute((int)fieldLength);
FileLoad.ValidField(expected, fieldValue, expectedLength).Should().BeFalse();
}
[Test]
public void ShouldBeValidFileName()
{
var defaultPage = new _Default();
_fileLoad = new FileLoad(defaultPage);
_fileLoad.IsValidFileName("this.csv").Should().BeTrue();
}
[Test]
public void ShouldThrowException()
{
_fileLoad = new FileLoad();
LoadedFile currentFile = new LoadedFile
{
FileName = "dummy.txt",
FileData = null,
ValidRows = new List<DataObject>(),
InvalidRows = new List<string>(),
Exceptions = new List<ExceptionMessages>()
};
Assert.That(()=> _fileLoad.LoadFile(true, true, currentFile), Throws.Exception);
}
[Test]
public void ShouldNotThrowException()
{
_fileLoad = new FileLoad();
LoadedFile currentFile = new LoadedFile
{
FileName = "dummy.csv",
FileData = null,
ValidRows = new List<DataObject>(),
InvalidRows = new List<string>(),
Exceptions = new List<ExceptionMessages>()
};
_fileLoad.UpdatesForDatabase = UpdateTestDatabase;
Assert.DoesNotThrow(() => _fileLoad.LoadFile(true, true, currentFile));
}
[TestCase("dummy.txt")]
[TestCase("dummy.vsc")]
[TestCase(null)]
[TestCase("")]
public void ShouldReturnFalseForInvalidFileExtension(string fileName)
{
_fileLoad = new FileLoad();
_fileLoad.IsValidFileName(fileName).Should().BeFalse();
}
[TestCase("dummy.Csv")]
[TestCase("dummy.csv")]
[TestCase("dummy.CSV")]
public void ShouldReturnTrueForValidCsvFileExtension(string fileName)
{
_fileLoad = new FileLoad();
_fileLoad.IsValidFileName(fileName).Should().BeTrue();
}
}
}
<file_sep>using System;
namespace CsvParser.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class FixedLengthAttribute : Attribute
{
public int FieldLength { get; }
public FixedLengthAttribute(int fieldLength)
{
FieldLength = fieldLength;
}
}
}<file_sep>using System.Collections.Generic;
using System.IO;
namespace CsvParser
{
public class LoadedFile
{
public string FileName { get; set; }
public StreamReader FileData { get; set; }
public List<DataObject> ValidRows { get; set; }
public List<string> InvalidRows { get; set; }
public List<ExceptionMessages> Exceptions { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using CsvParser.Attributes;
namespace CsvParser
{
public class FileLoad
{
private readonly _Default _fileLoadPage;
readonly string[] _allowedExtensions = { ".csv" };
public Action<LoadedFile> UpdatesForDatabase = UpdateDatabase;
public FileLoad()
{
}
public FileLoad(_Default fileLoadPage)
{
_fileLoadPage = fileLoadPage;
}
internal bool IsValidFileName(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return false;
}
return _allowedExtensions.Any(x => x.Contains(System.IO.Path.GetExtension(fileName).ToLower()));
}
private bool ValidFile(LoadedFile currentFile)
{
if (!IsValidFileName(currentFile.FileName) && currentFile.FileData == null)
{
return false;
}
string line;
long rowNumber = 1;
var invalidDataRows = new List<ExceptionMessages>();
while ((line = currentFile.FileData?.ReadLine()) != null)
{
var maxNumberOfItems = typeof(DataObject).GetProperties().Count();
var minNumberOfItems = 5;
var rowDataItems = line.Split(',');
ValidateIncorrectNumberOfColumns(currentFile, rowDataItems, maxNumberOfItems, rowNumber, line, minNumberOfItems);
if (rowDataItems.Length == maxNumberOfItems)
{
var lineToValidate = ConvertLineToDataObject(rowDataItems);
var properties = GetOrderedProperties(typeof(DataObject));
foreach (var property in properties)
{
var m = property.GetGetMethod();
var expectedType =
(ExpectedDataTypeAttribute)property.GetCustomAttribute(typeof(ExpectedDataTypeAttribute),
false);
var fieldLength =
(FixedLengthAttribute)property.GetCustomAttribute(typeof(FixedLengthAttribute), false);
var fieldValue = (string)m.Invoke(lineToValidate, null);
if (!ValidField(expectedType, fieldValue, fieldLength))
{
LogError(currentFile, rowNumber);
return false;
}
}
AddValidRow(currentFile, lineToValidate);
}
rowNumber++;
}
currentFile.Exceptions = invalidDataRows;
return true;
}
private static void LogError(LoadedFile currentFile, long rowNumber)
{
currentFile.Exceptions.Add(new ExceptionMessages
{
ErrorMessage = "Invalid data in row",
FileName = currentFile.FileName,
RowNumber = rowNumber
});
}
internal static DataObject ConvertLineToDataObject(string[] rowDataItems)
{
var lineToValidate = new DataObject
{
Column1 = rowDataItems[0],
Column2 = rowDataItems[1],
Column3 = rowDataItems[2],
Column4 = rowDataItems[3],
Column5 = rowDataItems[4],
Column6 = rowDataItems[5]
};
return lineToValidate;
}
internal static bool ValidField(ExpectedDataTypeAttribute expectedType, string fieldValue,
FixedLengthAttribute fieldLength)
{
if (string.IsNullOrEmpty(fieldValue))
{
return false;
}
switch (expectedType.FieldType.Name)
{
case "Guid":
Guid validGuid;
if (!Guid.TryParse(fieldValue, out validGuid))
{
return false;
}
break;
case "String":
if (fieldLength == null || fieldValue.Length > fieldLength.FieldLength)
{
return false;
}
break;
case "DateTime":
DateTime validDateTime;
if (!DateTime.TryParse(fieldValue, out validDateTime))
{
return false;
}
break;
case "Double":
double validDouble;
if (!double.TryParse(fieldValue, out validDouble))
{
return false;
}
break;
case "Int32":
Int32 validInt;
if (!Int32.TryParse(fieldValue,out validInt))
{
return false;
}
break;
default:
return false;
}
return true;
}
private static IEnumerable<PropertyInfo> GetOrderedProperties(Type type)
{
var properties = type.GetProperties();
Dictionary<int, PropertyInfo> orderedProperties = new Dictionary<int, PropertyInfo>();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(ColumnAttribute), false);
var attribute = (ColumnAttribute)attributes[0];
int nameOrderBy = attribute.ColumnNumber;
orderedProperties.Add(nameOrderBy, property);
}
return orderedProperties.OrderBy(x => x.Key).Select(x => x.Value).ToList();
}
internal static void AddValidRow(LoadedFile currentFile, DataObject validLine)
{
if (!string.IsNullOrEmpty(validLine.Column1)
&& !string.IsNullOrEmpty(validLine.Column2)
&& !string.IsNullOrEmpty(validLine.Column3)
&& !string.IsNullOrEmpty(validLine.Column4)
&& !string.IsNullOrEmpty(validLine.Column5)
&& !string.IsNullOrEmpty(validLine.Column6))
{
currentFile.ValidRows.Add(validLine);
}
}
internal static void ValidateIncorrectNumberOfColumns(LoadedFile currentFile, string[] rowDataItems, int maxNumberOfItems,
long rowNumber, string line, int minNumberOfItems)
{
if (rowDataItems.Length > maxNumberOfItems)
{
currentFile.Exceptions.Add(new ExceptionMessages
{
ErrorMessage = "Too many items in row",
FileName = currentFile.FileName,
RowNumber = rowNumber
});
currentFile.InvalidRows.Add(line);
}
if (rowDataItems.Length < minNumberOfItems)
{
currentFile.Exceptions.Add(new ExceptionMessages
{
ErrorMessage = "Too few items in row",
FileName = currentFile.FileName,
RowNumber = rowNumber
});
currentFile.InvalidRows.Add(line);
}
}
internal void LoadFile(bool isPostBack, bool isFileValid, LoadedFile currentFile)
{
if (isPostBack)
{
if (isFileValid)
{
if (ValidFile(currentFile))
{
try
{
UpdatesForDatabase.Invoke(currentFile);
}
catch (Exception e)
{
throw new Exception($"Issues Found Updating Database: {e.Message}");
}
}
else
{
throw new Exception("Issues Found with Invalid File");
}
}
}
}
private static void UpdateDatabase(LoadedFile currentFile)
{
SqlConnection conn =
new SqlConnection(
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\FileStorage.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand(
" INSERT INTO FileStore " + " Values (@Id, @FileName, @FileExtension, @FileData, @SuccessfulRowCount) ", conn);
cmd.Parameters.AddWithValue("@Id", Guid.NewGuid());
cmd.Parameters.AddWithValue("@FileName", currentFile.FileName);
cmd.Parameters.AddWithValue("@FileExtension", "csv");
cmd.Parameters.AddWithValue("@FileData", currentFile.FileData);
cmd.Parameters.AddWithValue("@SuccessfulRowCount", currentFile.ValidRows.Count);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CsvParser
{
public partial class _Default : Page
{
private bool _isPostBack;
private bool _isFileValid;
public Func<string, string> Result = DisplayValidationResults;
private readonly FileLoad _fileLoad;
public _Default()
{
_fileLoad = new FileLoad(this);
}
private static string DisplayValidationResults(string result)
{
if (string.IsNullOrEmpty(result))
{
return string.Empty;
}
return result;
}
protected void Page_Load(object sender, EventArgs e)
{
viewResult.Text = DisplayValidationResults(null);
if (!_isPostBack)
{
using (SqlConnection con = new SqlConnection(
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\FileStorage.mdf;Integrated Security=True")
)
{
using (SqlCommand cmd = new SqlCommand("SELECT Distinct FileName FROM FileStore"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
fileSelectionDropDown.DataSource = cmd.ExecuteReader();
fileSelectionDropDown.DataTextField = "FileName";
fileSelectionDropDown.DataValueField = "FileName";
fileSelectionDropDown.DataBind();
con.Close();
}
}
fileSelectionDropDown.Items.Insert(0, new ListItem("--Select File--", "0"));
}
}
protected void UploadFile_Click(object sender, EventArgs e)
{
_isPostBack = IsPostBack;
if (_isPostBack)
{
if (fileLoad.HasFile)
{
LoadedFile currentFile = new LoadedFile
{
FileName = fileLoad.FileName,
FileData = new StreamReader(fileLoad.PostedFile.InputStream),
ValidRows = new List<DataObject>(),
InvalidRows = new List<string>(),
Exceptions = new List<ExceptionMessages>()
};
_fileLoad.LoadFile(_isPostBack, fileLoad.HasFile, currentFile);
string results;
if (currentFile.ValidRows.Count > 0)
{
results =
$"File Loaded Successfully with the following: Valid Rows {currentFile.ValidRows.Count}, Invalid Rows {currentFile.InvalidRows.Count}";
}
else
{
results = "Incorrect file name or No valid rows in file";
}
viewResult.Text = DisplayValidationResults(results);
}
}
PopulateFileSelectionDropDown();
}
private void PopulateFileSelectionDropDown()
{
if (_isPostBack)
{
using (SqlConnection con =
new SqlConnection(
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\FileStorage.mdf;Integrated Security=True")
)
{
using (SqlCommand cmd = new SqlCommand("SELECT FileName FROM FileStore"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
fileSelectionDropDown.DataSource = cmd.ExecuteReader();
fileSelectionDropDown.DataTextField = "FileName";
fileSelectionDropDown.DataValueField = "FileName";
fileSelectionDropDown.DataBind();
con.Close();
}
}
fileSelectionDropDown.Items.Insert(0, new ListItem("--Select File--", "0"));
}
}
}
}<file_sep>using System;
using CsvParser.Attributes;
namespace CsvParser
{
public class DataObject
{
[Column(1)]
[ExpectedDataType(typeof(Guid))]
public string Column1 { get; set; }
[Column(2)]
[ExpectedDataType(typeof(String))]
public string Column2 { get; set; }
[Column(3)]
[ExpectedDataType(typeof(DateTime))]
public string Column3 { get; set; }
[Column(4)]
[ExpectedDataType(typeof(Int32))]
public string Column4 { get; set; }
[Column(5)]
[ExpectedDataType(typeof(Double))]
public string Column5 { get; set; }
[Column(6)]
[ExpectedDataType(typeof(String))]
public string Column6 { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsvParser.Interfaces
{
interface IFileLoad
{
string[] GetAllowedExtensions { get; set; }
bool ValidFileName(string fileName);
void LoadFile(bool isPostBack, bool isFileValid, string fileName);
}
}
<file_sep>namespace CsvParser
{
public class ExceptionMessages
{
public string FileName { get; set; }
public long RowNumber { get; set; }
public string ErrorMessage { get; set; }
}
} | 098f1bdcf2d967d31055f038dd7a7910ee9f960b | [
"C#"
] | 10 | C# | JEnsor247/TechnicalTestFileLoad | 882de372c314313da19c2168191bebb207557ae1 | f3de1f3cd75613298b86acda792ca87286e52627 |
refs/heads/master | <file_sep>import pyxel
from plugins.enum import Enum
from plugins.geometry import Point, Size
from plugins.sprite import Sprite, Anchor
from typing import Any
# Possible states for the line
class LineState(Enum):
STATE_NORMAL = 0
STATE_HIGH = 1
STATE_LOW = 2
# Represents the line drawn on the graph.
#TODO Unfinished: Allow changing of speed
#TODO Unfinished: Allow for jumps of more than 1 * width to not break the line.
class Line():
def __init__(self, game_state : Any) -> None:
self.line_state = LineState.STATE_NORMAL
self.game_state = game_state
# Record positions of segments as height above some "middle" value
self.current_height : float = 0
self.velocity : float = 0
def set_display(self, line_display : Any) -> None:
self.line_display = line_display
self.low_border = line_display.low_border
self.low_bound = line_display.low_bound
self.high_border = line_display.high_border
def reset(self) -> None:
self.current_height = 0
self.line_display.reset()
def update(self) -> None:
self.current_height += self.velocity
self.velocity = 0
# Change state depending on current height
# Remember y increases as you go down the screen
if self.current_height < -self.high_border:
self.line_state = LineState.STATE_HIGH
elif self.current_height > -self.low_bound:
self.game_state.kill_player()
elif self.current_height > -self.low_border:
self.line_state = LineState.STATE_LOW
else:
self.line_state = LineState.STATE_NORMAL
self.line_display.set_current_height(self.current_height)
# method called to affect the line's velocity, whether by player or environment
def add_velocity(self, velocity_adjustment : float) -> None:
self.velocity += velocity_adjustment
# Interface used by the controller to add velocity to the line
class LineInterface():
def __init__(self, line : Any) -> None:
self.line = line
def add_velocity(self, velocity_adjustment : float) -> None:
self.line.add_velocity(velocity_adjustment)
# Interface used to get the current state of the line
class LineStateInterface():
def __init__(self, line : Any) -> None:
self.line = line
def get_current_line_state(self) -> Any:
return self.line.line_state
# The visual representation of the Line
class LineDisplay():
def __init__(self, length : float, low_border : float, high_border : float, low_bound : float, high_bound : float, color : int, width : int = 0) -> None:
self.length = length
self.low_border = low_border
self.high_border = high_border
self.low_bound = low_bound
self.high_bound = high_bound
self.color = color
self.width = width
self.arrow_sprite = Sprite(Point(32,0), Size(7,8), 0, 0)
# Record segments to be drawn as the heights they should be drawn at
self.segments : list[float] = []
def reset(self) -> None:
self.segments = []
def set_current_height(self, current_height : int) -> None:
# Add to back
self.segments.append(current_height)
while len(self.segments) > self.length:
# Remove from front
self.segments.pop(0)
def draw(self, start : Any) -> None:
x = start.x
# Draw backwards from the starting point
for index in range(len(self.segments)-1, -1, -1):
if self.segments[index] < -self.high_bound:
if index == len(self.segments)-1:
self.arrow_sprite.draw(Point(x,start.y - self.high_bound), Anchor(Anchor.MIDDLE))
else:
pyxel.circ(x, start.y + self.segments[index], self.width, self.color)
x -= 1
<file_sep>import pyxel
from plugins.geometry import Point, Proportion2D, Size
from plugins.window import Window
from plugins.sprite import Sprite, TextSprite, Anchor
from typing import Any, Callable, Optional
class MainMenuOption(TextSprite):
def __init__(self, text : str, col : int, func : Callable[["MainMenu"],None]) -> None:
super(MainMenuOption, self).__init__(text, col)
self.func = func
class StatefulMainMenuOption(MainMenuOption):
def __init__(self, text : str, format : str, col : int, func : Callable[["MainMenu"],None]) -> None:
super(StatefulMainMenuOption, self).__init__(text.format(format), col, func)
self.unformatted_text = text
self.format = format
def update_format(self, format : str) -> None:
self.format = format
def draw(self, at : Point, anchor_x : Anchor = Anchor(Anchor.LEFT), anchor_y : Anchor = Anchor(Anchor.TOP), colour : Optional[int] = None) -> None:
self.text = self.unformatted_text.format(self.format)
self.calculate_sizes()
super(StatefulMainMenuOption, self).draw(at, anchor_x, anchor_y, colour)
# Represents both the logic and the display of the Main Menu.
# Although not separating them is a break from my convention, the resulting code is much
# neater in this case, and there's no need for syncing up what the various menu options
# can be across two different classes.
class MainMenu(Window):
def __init__(self, start_game_interface : Any) -> None:
super(MainMenu, self).__init__(Proportion2D(0,0), Proportion2D(1,1))
self.start_game_interface = start_game_interface
self.bg_col = 0
self.text_col = 7
self.selected_col = 14
self.character_sprite = Sprite(Point(0,0), Size(32,40), 0, 0)
self.tutorial_menu_option = StatefulMainMenuOption("Tutorial: {}", "Yes", self.text_col, lambda main_menu: main_menu.update_tutorial_state())
def start_game_callback(main_menu : MainMenu) -> None:
main_menu.start_game_interface.start_game()
def quit_game_callback(main_menu : MainMenu) -> None:
pyxel.quit()
self.options = [
MainMenuOption("Start Game", self.text_col, start_game_callback),
#self.tutorial_menu_option,
MainMenuOption("Quit", self.text_col, quit_game_callback)
]
self.num_options = len(self.options)
self.current_option = 0
self.tutorial_active = True
self.credit_text = TextSprite("By <NAME>: @RjmcfDev", 7)
self.title = Sprite(Point(0,91), Size(67,23), 0, 0)
self.animated_col = 10
self.animated_col_list = [11,9,8,8,9]
self.current_animated_col_index = 0
self.frame_gap = 5
def update_tutorial_state(self) -> None:
self.tutorial_active = not self.tutorial_active
self.tutorial_menu_option.update_format("Yes" if self.tutorial_active else "No")
def move_down(self) -> None:
self.current_option = (self.current_option + 1) % self.num_options
def move_up(self) -> None:
self.current_option = (self.current_option - 1) % self.num_options
def select(self) -> None:
self.options[self.current_option].func(self)
def update(self) -> None:
if not pyxel.frame_count % self.frame_gap:
self.current_animated_col_index = (self.current_animated_col_index + 1) % len(self.animated_col_list)
pyxel.pal(self.animated_col, self.animated_col_list[self.current_animated_col_index])
def draw_before_children(self) -> None:
pyxel.rect(*self.corner, *self.size, self.bg_col)
self.character_sprite.draw(self.corner.br_of(self.size.scale2D(Proportion2D(0.5,0.2))), Anchor(Anchor.MIDDLE), Anchor(Anchor.MIDDLE))
self.title.draw(self.corner.br_of(self.size.scale2D(Proportion2D(0.5,0.4))), Anchor(Anchor.MIDDLE), Anchor(Anchor.MIDDLE))
distance_down = 0.6
seperator = 0.1
for i, option in enumerate(self.options):
option.draw(self.corner.br_of(self.size.scale2D(Proportion2D(0.5,distance_down + i*seperator))), Anchor(Anchor.MIDDLE), Anchor(Anchor.MIDDLE), self.selected_col if i == self.current_option else None)
self.credit_text.draw(self.corner.br_of(Size(0, self.size.y)), Anchor(Anchor.LEFT), Anchor(Anchor.BOTTOM))
<file_sep>import pyxel
from plugins.geometry import Proportion2D
from plugins.window import Window
from typing import Optional
# Represents a bar that can be filled. Bars can be horizontal or vertical, and fill in
# either direction. Stores how much it's filled as a percentage.
class FillableBar(Window):
def __init__(self, corner_prop : Proportion2D, size_prop : Proportion2D, is_vertical : bool, fill_positive : bool, back_colour : int, fill_colour : int, border_colour : Optional[int] = None) -> None:
super(FillableBar, self).__init__(corner_prop, size_prop)
self.percent_full : float = 0
self.is_vertical = is_vertical
self.fill_positive = fill_positive
self.back_colour = back_colour
self.fill_colour = fill_colour
self.border_colour = border_colour
# Method used to add an amount to the bar.
def adjust_bar(self, percent_difference : float) -> None:
self.set_bar(self.percent_full + percent_difference)
# Method used to set amount for bar
def set_bar(self, percent_full : float) -> None:
self.percent_full = percent_full
self.percent_full = min(self.percent_full, 1)
self.percent_full = max(0, self.percent_full)
def is_empty(self) -> bool:
return self.percent_full <= 0
def is_full(self) -> bool:
return self.percent_full >= 1
def draw_before_children(self) -> None:
pyxel.rect(*self.corner, *self.size, self.back_colour)
if self.is_vertical:
top_left_x = self.corner.x
top_left_y = self.corner.y if self.fill_positive else int(self.corner.y + (1-self.percent_full) * self.size.y)
width = self.size.x
height = self.percent_full * self.size.y
else:
top_left_x = self.corner.x if self.fill_positive else int(self.corner.x + (1-self.percent_full) * self.size.x)
top_left_y = self.corner.y
width = self.percent_full * self.size.x
height = self.size.y
pyxel.rect(top_left_x, top_left_y, width, height, self.fill_colour)
if self.border_colour != None:
pyxel.rectb(*self.corner, *self.size, self.border_colour)
<file_sep>from plugins.sprite import TextSprite
from controller import TimeDependentAffector
from line import LineState
from random import randint, random, choice
from typing import Any, Callable, Mapping
# Controls the environmental effects on the line. Essentially the enemy of the player.
class Environment():
def __init__(self, controller_interface : Any, threat_interface : Any, line_state_interface : Any) -> None:
self.controller_interface = controller_interface
self.controller_interface.add_affector(RandomPerturbationAffector())
self.threat_interface = threat_interface
self.line_state_interface = line_state_interface
# time before first Event
self.count = randint(200, 300)
# Possible events that exclusively push the line down
self.DOWN_EVENTS = {
"Chasing Criminal" : SlowStartStopAffector(1400, 300, False),
"No Time To Rest!" : SlowStartStopAffector(900, 400, False),
"Difficult Fight" : SlowStartStopAffector(1500, 100, False)
}
# Weight assigned to down events in weighted random selection
self.num_down = 10
# Possible events that exclusively push the line up
self.UP_EVENTS = {
"Time Pressure" : SlowStartStopAffector(1500, 300, True),
"Exposure To High Temperature" : SlowStartStopAffector(1200, 400, True),
"Refuelling" : SlowStartStopAffector(1400, 200, True)
}
# Weight assigned to up events in weighted random selection
self.num_up = 10
# Possible events that have a more complex effect on the line
self.SPECIAL_EVENTS = {"Poisoned": UpDownAffector(250, 500, 0.7, 1.7, self.controller_interface, True)}
# Weight assigned to special events in weighted random selection
self.num_special = 2
def set_character_display_text_interface(self, character_display_text_interface : Any) -> None:
self.character_display_text_interface = character_display_text_interface
def reset(self) -> None:
self.controller_interface.add_affector(RandomPerturbationAffector())
def update(self) -> None:
current_line_state = self.line_state_interface.get_current_line_state()
if current_line_state == LineState.STATE_NORMAL:
self.threat_interface.adjust_threat_percent(-0.3 / 100)
elif current_line_state == LineState.STATE_HIGH:
self.threat_interface.adjust_threat_percent(0.2 / 100)
elif current_line_state == LineState.STATE_LOW:
self.threat_interface.adjust_threat_percent(1 / 100)
self.count -= 1
if not self.count:
event_list = self.pick_random_event_list()
name = choice(list(event_list.keys()))
self.character_display_text_interface.add_text(TextSprite(name, 7), 30)
event = event_list[name]
event.reset()
self.controller_interface.add_affector(event)
self.count = self.set_timer()
# Picks random event list based on weighting
#TODO Investigate: Consider implementing weighted random options as plugin.
def pick_random_event_list(self) -> Mapping[str, TimeDependentAffector]:
total = self.num_down + self.num_up + self.num_special
self.chance_down = self.num_down / total
self.chance_up = self.chance_down + self.num_up / total
selection_num = random()
if selection_num < self.chance_down:
return self.DOWN_EVENTS
elif selection_num < self.chance_up:
return self.UP_EVENTS
else:
return self.SPECIAL_EVENTS
# Time between events
def set_timer(self) -> int:
return randint(300, 600)
# Affector that eases in and out of an effect, pushing either up or down
class SlowStartStopAffector(TimeDependentAffector):
def __init__(self, severity : float, lifetime : int, pushing_up : bool) -> None:
super(SlowStartStopAffector, self).__init__(lifetime)
self.severity = severity
self.pushing_up = pushing_up
def f(self, time : int) -> float:
abs_val = self.severity * self.curve(time / self.lifetime) / self.lifetime
return abs_val if self.pushing_up else -abs_val
def curve(self, percent_time : float) -> float:
return percent_time*percent_time*(1-percent_time)*(1-percent_time)
# Twin of the UpDownAffector, represents the second portion of that effect.
class InverseAffector(TimeDependentAffector):
def __init__(self, severity : float, lifetime : int, curve_func : Callable[[float], float]) -> None:
super(InverseAffector, self).__init__(lifetime)
self.severity = severity
self.curve = curve_func
def f(self, time : int) -> float:
return -self.severity * self.curve(time / self.lifetime) / self.lifetime
# Affector that pushes the line first in one direction then the other, by spawning the
# inverse affector at the end of its life.
class UpDownAffector(TimeDependentAffector):
def __init__(self, severity : float, lifetime : int, change_point : float, severity_difference : float, controller_interface : Any, up_initially : bool) -> None:
super(UpDownAffector, self).__init__(int(lifetime * change_point))
self.controller_interface = controller_interface
self.inverse_lifetime = int(lifetime * (1 - change_point))
self.severity_difference = severity_difference
self.severity = severity
self.curve = self.up_curve if up_initially else lambda x: -self.up_curve(x)
def f(self, time : int) -> float:
if self.is_finished():
self.add_inverse_affector()
return self.severity * self.curve(time / self.lifetime) / self.lifetime
def up_curve(self, percent_time : float) -> float:
return percent_time*(1-percent_time)
def add_inverse_affector(self) -> None:
inverse_affector = InverseAffector(self.severity * self.severity_difference, self.inverse_lifetime, self.curve)
self.controller_interface.add_affector(inverse_affector)
# Causes random movements in the line, gives it some life.
class RandomPerturbationAffector(TimeDependentAffector):
def __init__(self) -> None:
super(RandomPerturbationAffector, self).__init__(-1)
self.count = self.set_timer()
def f(self, time : int) -> float:
self.count -= 1
if not self.count:
# How far to move
val = randint(1,2)
pos = randint(0,1)
self.count = self.set_timer()
return val if pos else -val
return 0
def set_timer(self) -> int:
# Time between movements
return randint(10,50)
<file_sep>from plugins.window import Window
from plugins.geometry import Proportion2D
from bars import FillableBar
from typing import Any
# Logic for the threat to the player
class PlayerThreat():
def __init__(self, game_state : Any) -> None:
self.player_threat_percent : float = 0
self.game_state = game_state
def set_display(self, display : Any) -> None:
self.display = display
def set_player_threat_percent(self, threat_percent : float) -> None:
self.player_threat_percent = min(1, max(0, threat_percent))
self.display.set_player_threat_percent(self.player_threat_percent)
def update(self) -> None:
if self.player_threat_percent >= 1:
self.game_state.kill_player()
def reset(self) -> None:
self.set_player_threat_percent(0)
# Visual representation of the current threat to the player
class PlayerThreatWindow(Window):
def __init__(self, corner_prop : Proportion2D, size_prop : Proportion2D, background_col : int, border_col : int) -> None:
super(PlayerThreatWindow, self).__init__(corner_prop, size_prop)
self.background_col = background_col
self.foreground_col = 8
self.border_col = border_col
self.player_threat_display = FillableBar(Proportion2D(0,0), Proportion2D(1,1), True,False, self.background_col,self.foreground_col, self.border_col)
self.child_windows = [self.player_threat_display]
def set_player_threat_percent(self, threat_percent : float) -> None:
self.player_threat_display.set_bar(threat_percent)
# Interface allowing the threat to the player to be set depending on how long they've been
# in the danger zones.
class PlayerThreatInterface():
def __init__(self, player_threat : PlayerThreat) -> None:
self.player_threat = player_threat
def adjust_threat_percent(self, threat_adjustment : float) -> None:
self.player_threat.set_player_threat_percent(self.player_threat.player_threat_percent + threat_adjustment)
<file_sep>from plugins.geometry import Point, Proportion2D, Size
from typing import Optional
# Represents a game-window in code.
# Defines itself in terms of proportions of its parent that it takes up,
# i.e. how far in x and y the top left corner is, and how much width and height is used.
# Windows are hierarchical, and so have a list of child_windows that they manage.
#TODO Investigate: Validate on whether stuff is outside the parent?
class Window():
def __init__(self, corner_prop : Proportion2D, size_prop : Proportion2D, parent_corner : Optional[Point] = None, parent_size : Optional[Size] = None) -> None:
self.corner_prop = corner_prop
self.size_prop = size_prop
if parent_corner is not None and parent_size is not None:
self.calculate_dimensions(parent_corner, parent_size)
self.child_windows : list[Window] = []
def calculate_dimensions(self, parent_corner : Point, parent_size : Size) -> None:
self.corner = parent_corner.br_of(parent_size.scale2D(self.corner_prop))
self.size = parent_size.scale2D(self.size_prop)
def update(self) -> None:
for window in self.child_windows:
window.update()
def draw(self, parent_corner : Point, parent_size : Size) -> None:
self.calculate_dimensions(parent_corner, parent_size)
self.draw_before_children()
for child in self.child_windows:
child.draw(self.corner, self.size)
self.draw_after_children()
# Overriden to draw things for this specific child before further children
def draw_before_children(self) -> None:
pass
# Overriden to draw things for this specific child after further children
def draw_after_children(self) -> None:
pass
# Represents the TopLevelWindow, ie, the parent of all other windows
class TopLevelWindow():
def __init__(self, size : Size) -> None:
self.size = size
self.windows : list[Window] = []
def update(self) -> None:
for window in self.windows:
window.update()
def draw(self) -> None:
for window in self.windows:
window.draw(Point(0,0), self.size)
<file_sep>from core import Core
class App:
def __init__(self) -> None:
self.core = Core()
self.core.start()
App()
# use the following console command to type check
# mypy bi-onic.py --namespace-packages --ignore-missing-imports
<file_sep>import pyxel
from typing import Any
# Represents something that can affect the graphs, whose effect changes with time.
class TimeDependentAffector():
INFINITE = -1
def __init__(self, lifetime : int) -> None:
# if lifetime == 0, effect lasts one tick,
# if lifetime == TimeDependentAffector.INFINITE, effect lasts forever
self.lifetime = lifetime
self.time_elapsed = 0
def is_finished(self) -> bool:
return self.time_elapsed > self.lifetime if self.lifetime != TimeDependentAffector.INFINITE else False
def reset(self) -> None:
self.time_elapsed = 0
# Updates the lifecycle, and returns the effect for this particular tick
def get_effect_for_this_tick(self) -> float:
self.time_elapsed += 1
return self.f(self.time_elapsed)
# Can be used to work out how much for this affector will deliver before finishing
def remaining_affect(self) -> float:
return 0
# Can be set or overrided to determine how the effect changes over time.
def f(self, time : int) -> float:
return 0
# Keeps track of factors that affect the graph's velocity, either from the player or
# the environment.
class Controller():
def __init__(self, line_interface : Any) -> None:
self.line_interface = line_interface
self.reservoir = 0
# List of things that are currently affecting the graph.
self.affectors : list[TimeDependentAffector] = []
def set_character_display_reservoir_interface(self, character_display_reservoir_interface : Any) -> None:
self.character_display_reservoir_handle = character_display_reservoir_interface
def update(self) -> None:
for index in range(len(self.affectors) -1, -1, -1):
affector = self.affectors[index]
# Here we scale for the "y increases downwards" thing
self.line_interface.add_velocity(-affector.get_effect_for_this_tick())
if (affector.is_finished()):
self.affectors.remove(affector)
self.character_display_reservoir_handle.empty_down_reservoir()
for affector in self.affectors:
self.character_display_reservoir_handle.add_down_reservoir_amount(affector.remaining_affect())
def reset(self) -> None:
self.reservoir = 0
self.affectors = []
# Interface to allow things (player or environment) to add things that will affect the
# graph
class ControllerInterface():
def __init__(self, controller : Controller) -> None:
self.controller = controller
def add_affector(self, affector : TimeDependentAffector) -> None:
self.controller.affectors.append(affector)
<file_sep>import pyxel
from plugins.window import Window
from plugins.geometry import Point, Size, Vector, Proportion2D
from plugins.sprite import Sprite, TextSprite, Anchor
from palette_settings import Palette, PALETTE
from resource_settings import RESOURCE
from typing import Any, Callable
# The base for windows used for debugs. Defines a key the user can use to toggle to it,
# which defines the equality relation
class DebugWindow(Window):
def __init__(self, title : str, toggle_key : int) -> None:
super(DebugWindow, self).__init__(Proportion2D(0,0), Proportion2D(1,1))
self.title = title
self.toggle_key = toggle_key
def __eq__(self, other : object) -> bool:
# We only want to compare ourselves by key with other Debug windows
if isinstance(other, DebugWindow):
return self.toggle_key == other.toggle_key
else:
return super(DebugWindow, self).__eq__(other)
def __hash__(self) -> int:
return self.toggle_key
# Allows for debugging of TextSprites
class TextImager(DebugWindow):
def __init__(self) -> None:
super(TextImager, self).__init__("Text Imager", pyxel.KEY_S)
self.text_sprite = TextSprite("Sample Text", 8)
def draw_before_children(self) -> None:
pyxel.line(*self.size.scale2D(Size(0.5,0)), *self.size.scale2D(Size(0.5,1)), 7)
pyxel.line(*self.size.scale2D(Size(0,0.5)), *self.size.scale2D(Size(1,0.5)), 7)
self.text_sprite.draw(self.corner.br_of(self.size.scale2D(Size(0.5,0.5))), Anchor(Anchor.MIDDLE), Anchor(Anchor.MIDDLE))
# Shows a representation of an affector, input (0,1), output (0,1)
class GraphImager(DebugWindow):
def __init__(self) -> None:
super(GraphImager, self).__init__("Graph Imager", pyxel.KEY_G)
self.graph_tl = Point(10,10)
self.graph_size = Size(100, 70)
self.cutoff = 0.9
def f(self, x : float) -> float:
if x < self.cutoff:
return self.up_curve(x / self.cutoff)
return -self.up_curve((x-self.cutoff) / (1-self.cutoff))
def up_curve(self, t : float) -> float:
return t*(1-t)
def g(self, x : float) -> float:
return x * (1-x)
def h(self, x : float) -> float:
return -self.g(x)
def draw_before_children(self) -> None:
pyxel.rectb(*self.graph_tl, *self.graph_size, 7)
pyxel.rectb(*self.graph_tl.br_of(Size(0, self.graph_size.y)), *self.graph_size.scale2D(Size(1,2)), 7)
self.draw_func_with_col(self.f, 8)
self.draw_func_with_col(self.g, 9)
self.draw_func_with_col(self.h, 10)
def draw_func_with_col(self, func : Callable[[float], float], col : int) -> None:
for x in range(int(self.graph_size.x)):
current_y = self.graph_size.y * func(x / self.graph_size.x)
current_y = self.graph_tl.y + self.graph_size.y - current_y
current_x = self.graph_tl.x + x
if x == 0:
previous_y = current_y
previous_x = current_x
pyxel.line(previous_x, previous_y, current_x, current_y, col)
previous_x = current_x
previous_y = current_y
# Simply shows the palette currently being used
class PaletteViewer(DebugWindow):
def __init__(self) -> None:
super(PaletteViewer, self).__init__("Palette Viewer", pyxel.KEY_O)
def draw_palette(self, x : int, y : int, col : int) -> None:
col_val = PALETTE.get_palette()[col]
hex_col = "#{:06X}".format(col_val)
pyxel.rect(x, y, 8, 8, col)
pyxel.text(x + 16, y + 1, hex_col, 7)
pyxel.text(x + 3 - (col // 10) * 2, y + 2, "{}".format(col), 7 if col < 6 else 0)
def draw_before_children(self) -> None:
for i in range(16):
self.draw_palette(self.corner.xInt() + 2 + (i % 4) * 50, self.corner.yInt() + 4 + (i // 4) * 15, i)
# The editor can only display the default palette as far as I know. When editing an image,
# you can't actually see how it will look if you use a different palette. This window
# displays an image using the current palette used in game, so you can see how it will
# actually look. You can hot-reload the resource using the Enter key.
class ImageViewer(DebugWindow):
def __init__(self, palette : Palette) -> None:
super(ImageViewer,self).__init__("Image Viewer", pyxel.KEY_I)
self.img_bank = 0
self.source_top_left = Vector(0, 12)
self.source_sections = Size(4,8)
self.palette = palette
self.display_top_left = Vector(15,20)
def update(self) -> None:
super(ImageViewer, self).update()
if pyxel.btnp(pyxel.KEY_ENTER):
pyxel.load(RESOURCE)
def draw_before_children(self) -> None:
pyxel.text(*self.corner,self.title, 7)
pyxel.text(*self.corner.br_of(Size(0,6)), "Showing from (" + str(self.source_top_left.x) + ", " + str(self.source_top_left.y) + ") to (" + str(self.source_top_left.x + self.source_sections.x) + ", " + str(self.source_top_left.y + self.source_sections.y) + ") of image bank " + str(self.img_bank), 7)
pyxel.text(*self.corner.br_of(Size(0,12)), "Using palette: {}".format(self.palette.name), 7)
pyxel.blt(*self.corner.translate(self.display_top_left), self.img_bank, *self.source_top_left.scale(8), *self.source_top_left.add(Vector(self.source_sections.x,self.source_sections.y)).scale(8))
pyxel.rectb(*self.corner.translate(self.display_top_left.add(Vector(-1,-1))), *self.source_sections.scale(8), 7)
# Takes an image from the resource and tiles it as wide and tall as you want.
# Can hot-reload the image using the Enter key.
class Tiler(DebugWindow):
def __init__(self) -> None:
super(Tiler,self).__init__("Tiler", pyxel.KEY_T)
self.sprite = Sprite(Point(1*8,6*8), Size(5*8,5*8), 0)
self.source_size = self.sprite.source_size
self.repetitions_x = 3
self.repetitions_y = 3
self.display_top_left = Vector(20,20)
def update(self) -> None:
super(Tiler,self).update()
if pyxel.btnp(pyxel.KEY_ENTER):
pyxel.load(RESOURCE)
def draw_before_children(self) -> None:
for col in range(self.repetitions_x):
for row in range(self.repetitions_y):
self.sprite.draw(self.corner.br_of(self.source_size.scale2D(Size(col,row))).translate(self.display_top_left))
<file_sep>import pyxel
from root import Root
from game_state import GameState
from player_controller import PlayerController
from environment import Environment
from line import Line, LineInterface, LineStateInterface
from controller import Controller, ControllerInterface
from player_threat import PlayerThreat, PlayerThreatInterface
from score_keeper import ScoreKeeper, ScoreKeeperEndGameDelegate
from main_menu import MainMenu
from typing import Any
# Manages the overall functioning of the game. Owns all the components, and makes sure
# they are updated correctly.
# Also owns root window, and makes sure it knows when to draw.
# If a logical component needs a reference to a display element, the convention is to pass
# the logical component to the root window and allow it to set the correct display element.
class Core():
def __init__(self) -> None:
# Setup Logical stuff
self.game_state = GameState()
self.player_threat = PlayerThreat(self.game_state)
self.line = Line(self.game_state)
line_state_interface = LineStateInterface(self.line)
self.controller = Controller(LineInterface(self.line))
controller_interface = ControllerInterface(self.controller)
self.player_controller = PlayerController(controller_interface)
self.environment = Environment(controller_interface, PlayerThreatInterface(self.player_threat), line_state_interface)
self.score_keeper = ScoreKeeper(line_state_interface)
self.game_state.add_kill_player_delegate(ScoreKeeperEndGameDelegate(self.score_keeper))
self.main_menu = MainMenu(StartGameInterface(self))
# Setup display stuff
self.root_window = Root(self.game_state, self.main_menu)
self.root_window.set_player_threat_display(self.player_threat)
self.root_window.set_line_display(self.line)
self.root_window.set_character_display_reservoir_interface(self.controller)
self.root_window.set_character_display_control_interface(self.player_controller)
self.root_window.set_character_display_text_interface(self.environment)
self.root_window.set_score_display(self.score_keeper)
# State that we start at the Main Menu
self.root_window.switch_to_main_menu()
def update(self) -> None:
if self.game_state.in_game_mode():
self.update_game_mode()
elif self.game_state.in_main_menu_mode():
self.update_main_menu_mode()
else:
print("Invalid game mode", self.game_state.game_mode, "detected")
quit()
def update_game_mode(self) -> None:
if self.game_state.is_game_playing():
if pyxel.btnp(pyxel.KEY_P):
self.game_state.toggle_paused()
if not self.game_state.paused:
self.player_threat.update()
self.player_controller.update()
self.controller.update()
self.line.update()
self.score_keeper.update()
self.environment.update()
# Enable us to show debug even when paused
self.root_window.update()
else:
if pyxel.btnp(pyxel.KEY_R):
to_be_reset : list[Any] = [
self.game_state, self.player_threat, self.line, self.controller,
self.player_controller, self.environment, self.score_keeper,
self.root_window
]
for thing in to_be_reset:
thing.reset()
def update_main_menu_mode(self) -> None:
if pyxel.btnp(pyxel.KEY_UP):
self.main_menu.move_up()
elif pyxel.btnp(pyxel.KEY_DOWN):
self.main_menu.move_down()
elif pyxel.btnp(pyxel.KEY_ENTER):
self.main_menu.select()
# Allow debug windows still
self.root_window.update()
def start_game(self) -> None:
self.game_state.start_game()
self.root_window.switch_to_game()
def start(self) -> None:
pyxel.run(self.update, self.root_window.draw)
# Interface allowing MainMenu to start the game
class StartGameInterface:
def __init__(self, core : Core) -> None:
self.core = core
def start_game(self) -> None:
self.core.start_game()
<file_sep># Defines resources to be loaded
RESOURCE = "assets/bionic_resources.pyxres"
<file_sep>[mypy]
[mypy-pyxel.*]
ignore_missing_imports = True
<file_sep>import pyxel
from plugins.window import Window
from plugins.geometry import Proportion2D, Vector
from plugins.sprite import Anchor, TextSprite
from bars import FillableBar
from player_controller import DownAffector
from player_threat import PlayerThreatWindow
from score_keeper import ScoreDisplayWindow
from typing import Any
# The window that shows the 'HUD' elements, including:
# Control UI
# Threat UI
# Text descriptions of active events
# TODO Unfinished: Show Character state
class CharacterDisplay(Window):
def __init__(self) -> None:
super(CharacterDisplay, self).__init__(Proportion2D(0,0), Proportion2D(1,0.4))
self.background = 1
self.control_border = 7
self.up_control = FillableBar(Proportion2D(0.9,0.1), Proportion2D(0.05,0.4), True,False, self.background,14, self.control_border)
self.down_control = FillableBar(Proportion2D(0.9,0.5), Proportion2D(0.05,0.4), True,True, self.background,3, self.control_border)
self.down_reservoir = FillableBar(Proportion2D(0.85,0.5), Proportion2D(0.05,0.4), True,False, self.background,3, self.control_border)
self.player_threat_display = PlayerThreatWindow(Proportion2D(0.05,0.1), Proportion2D(0.05,0.8), self.background, self.control_border)
self.score_display = ScoreDisplayWindow()
# Maintain mapping of active sprites to the amount of time we should display them for
self.active_text_sprites : dict[TextSprite, int] = {}
self.child_windows = [self.up_control, self.down_control, self.down_reservoir, self.player_threat_display, self.score_display]
def set_character_display_reservoir_interface(self, controller : Any) -> None:
controller.set_character_display_reservoir_interface(CharacterDisplayReservoirInterface(self))
def set_character_display_control_interface(self, player_controller : Any) -> None:
player_controller.set_character_display_control_interface(CharacterDisplayControlInterface(self))
def set_character_display_text_interface(self, environment : Any) -> None:
environment.set_character_display_text_interface(CharacterDisplayTextInterface(self))
def set_score_display(self, score_keeper : Any) -> None:
score_keeper.set_display(self.score_display)
def reset(self) -> None:
self.up_control.set_bar(0)
self.down_control.set_bar(0)
self.down_reservoir.set_bar(0)
self.active_text_sprites = {}
self.score_display.reset()
def empty_down_reservoir(self) -> None:
self.down_reservoir.set_bar(0)
def add_down_reservoir_amount(self, percent_increase : float) -> None:
self.down_reservoir.adjust_bar(percent_increase)
def set_player_threat_display(self, player_threat : Any) -> None:
player_threat.set_display(self.player_threat_display)
def add_text(self, text_sprite : TextSprite, duration : int) -> None:
self.active_text_sprites[text_sprite] = duration
def update(self) -> None:
for text_sprite in list(self.active_text_sprites.keys()):
self.active_text_sprites[text_sprite] -= 1
if self.active_text_sprites[text_sprite] == 0:
del self.active_text_sprites[text_sprite]
def draw_before_children(self) -> None:
pyxel.rect(*self.corner, *self.size, self.background)
for text_sprite in self.active_text_sprites:
text_sprite.draw(self.corner.translate(Vector(*self.size.scale2D(Proportion2D(0.5,0.5)))), Anchor(Anchor.MIDDLE), Anchor(Anchor.MIDDLE))
# Interface for player_controller to use the control UI
class CharacterDisplayControlInterface():
def __init__(self, character_display : Any) -> None:
self.character_display = character_display
def set_up_control(self, percent : float) -> None:
self.character_display.up_control.set_bar(percent)
def set_down_control(self, percent : float) -> None:
self.character_display.down_control.set_bar(percent)
# Interface for controller to use the reservoir UI
class CharacterDisplayReservoirInterface():
def __init__(self, character_display : Any) -> None:
self.character_display = character_display
def empty_down_reservoir(self) -> None:
self.character_display.empty_down_reservoir()
def add_down_reservoir_amount(self, amount : float) -> None:
self.character_display.add_down_reservoir_amount(amount)
# Interface for the environment to display descriptions of active events
class CharacterDisplayTextInterface():
def __init__(self, character_display : Any) -> None:
self.character_display = character_display
def add_text(self, text_sprite : TextSprite, duration : int) -> None:
self.character_display.add_text(text_sprite, duration)
# Interface for environment to use Threat UI
class ThreatDisplayInterface():
def __init__(self, character_display : Any) -> None:
self.character_display = character_display
def set_threat_percentage(self, threat_percentage : float) -> None:
self.character_display.set_threat_percentage(threat_percentage)
<file_sep>import pyxel
from controller import TimeDependentAffector
from typing import Any
# Used by the Player to have an effect on the graph.
class PlayerController():
def __init__(self, controller_interface : Any) -> None:
self.controller_interface = controller_interface
self.up_percent : float = 0
self.down_percent : float = 0
def set_character_display_control_interface(self, character_display_control_interface : Any) -> None:
self.character_display_control_interface = character_display_control_interface
def reset(self) -> None:
self.up_percent = 0
self.down_percent = 0
def update(self) -> None:
if pyxel.btn(pyxel.KEY_UP):
self.add_up_control(0.02)
elif pyxel.btn(pyxel.KEY_DOWN):
self.add_down_control(0.02)
elif pyxel.btnp(pyxel.KEY_ENTER):
self.administer()
self.character_display_control_interface.set_up_control(self.up_percent)
self.character_display_control_interface.set_down_control(self.down_percent)
def add_up_control(self, percent_increase : float) -> None:
if self.down_percent == 0:
self.up_percent += percent_increase
self.up_percent = min(1, self.up_percent)
else:
self.down_percent -= percent_increase
self.down_percent = max(0, self.down_percent)
def add_down_control(self, percent_increase : float) -> None:
if self.up_percent == 0:
self.down_percent += percent_increase
self.down_percent = min(1, self.down_percent)
else:
self.up_percent -= percent_increase
self.up_percent = max(0, self.up_percent)
def administer(self) -> None:
if self.up_percent > 0:
up_affector = UpAffector(80, 80 * self.up_percent)
self.controller_interface.add_affector(up_affector)
self.up_percent = 0
if self.down_percent > 0:
down_affector = DownAffector(400, 1000 * self.down_percent)
self.controller_interface.add_affector(down_affector)
self.down_percent = 0
# Affector for the Up control
class UpAffector(TimeDependentAffector):
def __init__(self, lifetime : int, scale : float) -> None:
super(UpAffector, self).__init__(lifetime)
self.scale = scale
def f(self, time : int) -> float:
t = time / self.lifetime
return self.scale / self.lifetime * (1 - t) * (1 - t)
# Affector for the down control
class DownAffector(TimeDependentAffector):
def __init__(self, lifetime : int, scale : float) -> None:
super(DownAffector, self).__init__(lifetime)
self.scale = scale
self.remaining_affect_scale = 1 / 2000
def remaining_affect(self) -> float:
t = self.time_elapsed / self.lifetime
return self.scale * self.remaining_affect_scale * (4 * t*t*t*t*t - 15 * t*t*t*t + 20 * t*t*t - 10 * t*t + 1)
def f(self, time : int) -> float:
t = time / self.lifetime
return - self.scale / self.lifetime * t * (1 - t) * (1 - t) * (1 - t)
<file_sep>class Enum():
def __init__(self, value : int) -> None:
self.value = value
def __eq__(self, other : object) -> bool:
# first part allows accessing `value`, second checks for exact types
if isinstance(other, Enum) and type(self) == type(other):
return self.value == other.value
elif isinstance(other, int):
return self.value == other
else:
return NotImplemented
<file_sep>from typing import Any
class Delegate():
def execute(self, *args : Any, **kwargs : Any) -> None:
pass
<file_sep>import pyxel
# Represents a colour palette in code
# wraps a list of 16 colour codes and a name
class Palette():
def __init__(self, name : str) -> None:
self.name = name
self.internal_palette : list[int] = pyxel.DEFAULT_PALETTE
# Let's you overwrite a colour in the palette
def __setitem__(self, index : int, item : int) -> None:
if isinstance(index, tuple):
raise TypeError("only one index expected")
self.internal_palette[index] = item
# Used when we want to actually use the palette to render something
def get_palette(self) -> list[int]:
return self.internal_palette
# The standard palette to be used while playing the game
game_palette = Palette("game")
game_palette[1] = 0x7e2553
game_palette[2] = 0x8b4226
game_palette[10] = 0x000000 # Animated colour
game_palette[11] = 0xdd9060
game_palette[14] = 0xffec27
# The palette used to render characters for close up images on social media
character_palette = Palette("character")
character_palette[2] = 0x8b4226
character_palette[10] = 0xaa004d
character_palette[11] = 0xdd9060
# Spare palette used for testing stuff.
test_palette = Palette("test")
test_palette[13] = 0x8759ad
# The actual palette being used currently
# This is set when we initialise the game, so will need to quit and restart to have effect.
PALETTE = game_palette
<file_sep>import pyxel
from plugins.window import Window
from plugins.geometry import Point, Proportion2D, Size
from line import Line, LineDisplay
# Just fills itself with a given colour
class DangerRegion(Window):
def __init__(self, x_prop : float, y_prop : float, width_prop : float, height_prop : float, colour : int) -> None:
super(DangerRegion, self).__init__(Proportion2D(x_prop, y_prop), Proportion2D(width_prop, height_prop))
self.colour = colour
def draw_before_children(self) -> None:
pyxel.rect(*self.corner, *self.size, self.colour)
# The window within which the graph is drawn.
class GraphWindow(Window):
def __init__(self, parent_corner : Point, parent_size : Size) -> None:
super(GraphWindow, self).__init__(Proportion2D(0,0.4), Proportion2D(1,0.6), parent_corner, parent_size)
self.colour = 6
self.start_prop = Proportion2D(1/2, 1/2)
self.high_region_prop = 2/5
self.low_region_prop = 1/5
self.line_display = LineDisplay(150,
-(1-self.start_prop.y-self.low_region_prop)*self.size.y,
(self.start_prop.y-self.high_region_prop)*self.size.y,
(self.start_prop.y-1)*self.size.y,
self.start_prop.y*self.size.y,
12, 2)
self.danger_high = DangerRegion(0,0, 1,self.high_region_prop, 9)
self.danger_low = DangerRegion(0,1-self.low_region_prop, 1,self.low_region_prop, 8)
self.child_windows = [self.danger_high, self.danger_low]
def set_line_display(self, line : Line) -> None:
line.set_display(self.line_display)
def update(self) -> None:
super(GraphWindow, self).update()
def draw_before_children(self) -> None:
pyxel.rect(*self.corner, *self.size, self.colour)
def draw_after_children(self) -> None:
self.line_display.draw(self.corner.br_of(self.size.scale2D(self.start_prop)))
<file_sep>import pyxel
from plugins.window import TopLevelWindow, Window
from plugins.geometry import Size, Point
from plugins.sprite import TextSprite
from palette_settings import PALETTE
from graph import GraphWindow
from character_display import CharacterDisplay
from resource_settings import RESOURCE
from debug import ImageViewer, Tiler, PaletteViewer, GraphImager, TextImager
from typing import Any
# Determines whether we will allow DEBUG screens to be shown
DEBUG = True
# Represents the parent window that contains all the others. Controls switching of windows
# for debug and menu purposes.
# Makes sure that all child windows get told to draw at the right time
class Root(TopLevelWindow):
def __init__(self, game_state : Any, main_menu : Any) -> None:
super(Root, self).__init__(Size(255,160))
self.caption = "Bi-onic"
self.palette = PALETTE
self.game_state = game_state
# This line needs to come before any Pyxel imports are used, otherwise they can't
# be imported
pyxel.init(*self.size, caption=self.caption, palette=self.palette.get_palette())
pyxel.load(RESOURCE)
self.character_display_window = CharacterDisplay()
self.graph_area = GraphWindow(Point(0,0), self.size)
self.restart_text = TextSprite("Press R to Restart", 7)
self.paused_text = TextSprite("Paused...", 7)
self.game_windows = [self.character_display_window, self.graph_area]
self.main_menu_windows = [main_menu]
if DEBUG:
self.debug_windows = [ImageViewer(self.palette), Tiler(), PaletteViewer(), GraphImager(), TextImager()]
if len(self.debug_windows) != len(set(self.debug_windows)):
print("debug windows with duplicate keys detected")
quit()
def toggle_debug_window(self, window : Any) -> None:
if window not in self.windows:
self.previous_windows = self.windows
self.windows = [window]
else:
self.windows = self.previous_windows
def switch_to_game(self) -> None:
self.windows = self.game_windows
def switch_to_main_menu(self) -> None:
self.windows = self.main_menu_windows
def set_player_threat_display(self, player_threat : Any) -> None:
self.character_display_window.set_player_threat_display(player_threat)
def set_line_display(self, line : Any) -> None:
self.graph_area.set_line_display(line)
def set_character_display_reservoir_interface(self, controller : Any) -> None:
self.character_display_window.set_character_display_reservoir_interface(controller)
def set_character_display_control_interface(self, player_controller : Any) -> None:
self.character_display_window.set_character_display_control_interface(player_controller)
def set_character_display_text_interface(self, environment : Any) -> None:
self.character_display_window.set_character_display_text_interface(environment)
def set_score_display(self, score_display : Any) -> None:
self.character_display_window.set_score_display(score_display)
def reset(self) -> None:
for thing in [self.character_display_window]:
thing.reset()
def update(self) -> None:
super(Root, self).update()
if DEBUG:
for debug_window in self.debug_windows:
if pyxel.btnp(debug_window.toggle_key):
self.toggle_debug_window(debug_window)
def draw(self) -> None:
pyxel.cls(0)
super(Root, self).draw()
if self.game_state.in_game_mode():
if not self.game_state.is_game_playing():
self.restart_text.draw(Point(0,0))
elif self.game_state.paused:
self.paused_text.draw(Point(0,0))
<file_sep>from typing import Any, Callable, Generic, Iterator, TypeVar, Union
# Represents something that has an x and a y component, which can be unpacked using *
# to get (x,y)
class Unpackable2D():
def __init__(self, x : float, y : float) -> None:
self.x = x
self.y = y
# Hack to enable typing of unpacking
__iter__: Callable[['Unpackable2D'], Iterator[float]]
# Enables us to use * to unpack
def __getitem__(self, key : int) -> float:
if key == 0:
return self.x
elif key == 1:
return self.y
else:
raise IndexError()
def xInt(self) -> int:
return int(self.x)
def yInt(self) -> int:
return int(self.y)
# Represents a scale factor in 2D, with components clamped between 0 and 1
class Proportion2D(Unpackable2D):
def __init__(self, x : float, y : float) -> None:
super(Proportion2D, self).__init__(max(0, min(1, x)), max(0, min(1, y)))
# Represents the dimensions of a rectangle
class Size(Unpackable2D):
def __init__(self, x : float, y : float) -> None:
super(Size, self).__init__(x,y)
# Return the rectangle you get when you apply the supplied 2D scale to this rectangle
def scale2D(self, scale : Union['Size', Proportion2D]) -> 'Size':
return Size(self.x * scale.x, self.y * scale.y)
# Return the rectangle you get when you scale this one by the supplied float.
def scale(self, scale : float) -> 'Size':
return Size(self.x * scale, self.y * scale)
# Represents a displacement in 2D space.
class Vector(Unpackable2D):
def __init__(self, x : float, y : float) -> None:
super(Vector, self).__init__(x,y)
# Get this vector, scaled by the given float
def scale(self, scale : float) -> 'Vector':
return Vector(self.x * scale, self.y * scale)
# Get the sum of this vector and the other vector
def add(self, vector : 'Vector') -> 'Vector':
return Vector(self.x + vector.x, self.y + vector.y)
# Represents a Point in 2D space
class Point(Unpackable2D):
def __init__(self, x : float, y : float) -> None:
super(Point, self).__init__(x,y)
# Get the bottom-right corner of the box defined with this point as the top-left,
# and the dimensions determined by size.
def br_of(self, size : Size) -> 'Point':
return Point(self.x + size.x, self.y + size.y)
# Get the top-left corner of the box defined with this point as the bottom-right,
# and the dimensions determined by size.
def tl_of(self, size : Size) -> 'Point':
return Point(self.x - size.x, self.y - size.y)
# Return the Point you get when you translate this point by the given Vector
def translate(self, vector : Vector) -> 'Point':
return Point(self.x + vector.x, self.y + vector.y)
<file_sep>from plugins.delegate import Delegate
from plugins.enum import Enum
# Represents Game Modes that the game can be in
class GameMode(Enum):
MAIN_MENU = 0
GAME = 1
# Records the current state of the game including:
# Our current mode
# Whether the player is alive
# Whether the game is paused
class GameState():
def __init__(self) -> None:
self.game_playing = True
self.paused = False
self.game_mode = GameMode(GameMode.MAIN_MENU)
self.kill_player_delegates : list[Delegate] = []
def start_game(self) -> None:
self.game_mode = GameMode(GameMode.GAME)
def kill_player(self) -> None:
if self.game_playing:
self.game_playing = False
for delegate in self.kill_player_delegates:
delegate.execute()
def add_kill_player_delegate(self, delegate : Delegate) -> None:
self.kill_player_delegates.append(delegate)
def is_game_playing(self) -> bool:
return self.game_playing
def exit_to_menu(self) -> None:
self.game_mode = GameMode(GameMode.MAIN_MENU)
def in_game_mode(self) -> bool:
return self.game_mode == GameMode.GAME
def in_main_menu_mode(self) -> bool:
return self.game_mode == GameMode.MAIN_MENU
def toggle_paused(self) -> None:
self.paused = not self.paused
def reset(self) -> None:
self.game_playing = True
self.paused = False
<file_sep>from plugins.window import Window
from plugins.sprite import TextSprite, Anchor
from plugins.geometry import Proportion2D
from plugins.delegate import Delegate
from line import LineState
from typing import Any
class ScoreKeeper():
def __init__(self, line_state_interface : Any) -> None:
self.score = 0
self.frames_for_increase = 10
self.frames_for_increase_in_danger = 30
self.score_increase = 10
self.current_frame = 0
self.line_state_interface = line_state_interface
self.high_score = 0
def reset(self) -> None:
self.score = 0
self.current_frame = 0
def set_display(self, display : Any) -> None:
self.display = display
def increase_score(self, amount : int) -> None:
self.score += amount
self.display.update_text_for_score(self.score)
def on_game_ended(self) -> None:
if self.score > self.high_score:
self.high_score = self.score
self.display.on_game_ended(self.high_score)
def update(self) -> None:
self.current_frame += 1
if self.line_state_interface.get_current_line_state() == LineState.STATE_NORMAL:
if not self.current_frame % self.frames_for_increase:
self.increase_score(self.score_increase)
else:
if not self.current_frame % self.frames_for_increase_in_danger:
self.increase_score(self.score_increase)
class ScoreKeeperEndGameDelegate(Delegate):
def __init__(self, score_keeper : Any) -> None:
self.score_keeper = score_keeper
def execute(self, *args : Any, **kwargs : Any) -> None:
self.score_keeper.on_game_ended()
class ScoreDisplayWindow(Window):
def __init__(self) -> None:
super(ScoreDisplayWindow, self).__init__(Proportion2D(0,0), Proportion2D(1,1))
self.num_zeros = 5
self.update_text_for_score(0)
self.game_ended = False
def reset(self) -> None:
self.game_ended = False
def on_game_ended(self, high_score : int) -> None:
self.high_score_text = TextSprite("High Score: " + str(high_score).zfill(self.num_zeros), 7)
self.game_ended = True
def update_text_for_score(self, score : int) -> None:
self.score_text = TextSprite("Score: " + str(score).zfill(self.num_zeros), 7)
def draw_before_children(self) -> None:
self.score_text.draw(self.corner.br_of(self.size.scale2D(Proportion2D(0.5,0))), Anchor(Anchor.MIDDLE))
if self.game_ended:
self.high_score_text.draw(self.corner.br_of(self.size.scale2D(Proportion2D(0.5,0.1))), Anchor(Anchor.MIDDLE))
<file_sep>import pyxel
from plugins.geometry import Point, Size, Vector
from plugins.enum import Enum
from typing import Optional, Union
# Determines the relation of the origin to the sprite.
# e.g. x = LEFT, y = TOP means that the origin is in the top left of the image
#TODO Refactor: Should we store state actually? Gives us type checking...
class Anchor(Enum):
TOP = 0
MIDDLE = 1
BOTTOM = 2
LEFT = 3
RIGHT = 4
def justify(at : Point, size : Size, anchor_x : Anchor, anchor_y : Anchor) -> Point:
if anchor_x == Anchor.LEFT:
x_adjust : float = 0
elif anchor_x == Anchor.MIDDLE:
x_adjust = -size.x * 0.5
elif anchor_x == Anchor.RIGHT:
x_adjust = -size.x
else:
print("Invalid anchor_x value:", anchor_x)
pyxel.quit()
if anchor_y == Anchor.TOP:
y_adjust : float = 0
elif anchor_y == Anchor.MIDDLE:
y_adjust = -size.y * 0.5
elif anchor_y == Anchor.BOTTOM:
y_adjust = -size.y
else:
print("Invalid anchor_y value:", anchor_y)
pyxel.quit()
return at.translate(Vector(x_adjust, y_adjust))
# Represents an image that can be drawn
class Sprite():
def __init__(self, source_point : Point, source_size : Size, img_bank : int, transpar_col : Optional[int] = None) -> None:
self.source_point = source_point
self.source_size = source_size
self.img_bank = img_bank
self.transpar_col = transpar_col
def draw(self, at : Point, anchor_x : Anchor = Anchor(Anchor.LEFT), anchor_y : Anchor = Anchor(Anchor.TOP)) -> None:
at = justify(at, self.source_size, anchor_x, anchor_y)
pyxel.blt(*at, self.img_bank, *self.source_point, *self.source_size, self.transpar_col)
# Represents a bit of text that can be drawn
# Currently only supports a single line
class TextSprite():
def __init__(self, text : str, col : int):
self.text = text
self.col = col
self.char_width = 4
self.char_height = 6
self.calculate_sizes()
def calculate_sizes(self) -> None:
self.size = Size(len(self.text) * self.char_width, self.char_height)
def draw(self, at : Point, anchor_x : Anchor = Anchor(Anchor.LEFT), anchor_y : Anchor = Anchor(Anchor.TOP), colour : Optional[int] = None) -> None:
at = justify(at, self.size, anchor_x, anchor_y)
pyxel.text(*at, self.text, colour if colour else self.col)
<file_sep>Refactor out colours into file so can easily see clashes
Music and Sound
Tutorial
Show Character in Display
- Respond to threat level
Modes
- Story
- Input name
- End game
- Dialogue
^^^^^ IDEAL FOR GAME JAM ^^^^^
Graphics polish<file_sep># Bi-onic
GitHubGameOff Game Jam game about a human-machine hybrid struggling to survive.
When your human body starts to break down, can you use your bionic enhancements to keep yourself alive, all while still managing to save the world?
Made using the Pyxel engine for Python, which I've fallen in love with: https://github.com/kitao/pyxel
| ecc71946642927a7ee4051231c59cffe538f621b | [
"Markdown",
"Python",
"Text",
"INI"
] | 25 | Python | rjmcf/Bi-onic | dbe1046bd3ee50ad8ffd7430c6b4bf8c8442b6f2 | 1b306b8939030e43ae6b4c724d72d8ad46590a75 |
refs/heads/master | <file_sep>import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class DecisionTreeNode {
private DecisionTreeNode parent;
private LinkedList<DecisionTreeNode> children;
private HashMap<Object, Integer> attribMapForChildren;
private HashMap<DecisionTreeNode, Object> childMapForAttribs;
private int attributeNr;
private String classification;
/**
* Build a new inner node that splits the data at the given attribute number.
* @param parent The parent of the inner node or null if it is to be a root node.
* @param attribute The attribute at which to split the data.
*/
public DecisionTreeNode(DecisionTreeNode parent, int attribute) {
classification = null;
this.attributeNr = attribute;
children = new LinkedList<>();
attribMapForChildren = new HashMap<>();
childMapForAttribs = new HashMap<>();
this.parent = parent;
}
/**
* Build a new leaf node.
* @param parent The parent of the inner node or null if it is to be a root node.
* @param classification The classification that is given for data "arriving" at this node.
*/
public DecisionTreeNode(DecisionTreeNode parent, String classification) {
this.classification = classification;
children = null;
attribMapForChildren = null;
this.parent = parent;
}
/**
* Adds a child to this node (which needs to be an inner node).
* @param node The node that is to be added to this node.
* @param forAttribValue The attribute-value that leads to the new child.
*/
public void addChild(DecisionTreeNode node, Object forAttribValue) {
if (children == null)
throw new RuntimeException("Cannot add child to a leaf node.");
children.add(node);
attribMapForChildren.put(forAttribValue, children.size()-1);
childMapForAttribs.put(node, forAttribValue);
}
/**
* @return The children of this node as list.
*/
public List<DecisionTreeNode> getChildren() {
return children;
}
/**
* @return The parent of this node.
*/
public DecisionTreeNode getParent() {
return parent;
}
/**
* Classifies the given data by walking to a root node
* while checking the attributes of the data at each inner node
* to determine which path to take.
*
* @param de The data that is to be classified.
* @return The classification of the data according to the decision tree
* that sits below this node.
*/
public String findClassification(DataExample de) {
if (classification != null) return classification;
else return children.get(attribMapForChildren.get(de.getData(attributeNr))).findClassification(de);
}
/**
* @return The root of the tree that this node is part of.
*/
public DecisionTreeNode getRoot() {
if (parent == null) return this;
else return parent.getRoot();
}
public String toString() {
String s = "(";
if (classification == null) {
s = s + "Attrib. " + attributeNr + ": ";
for (DecisionTreeNode c : children) {
s = s + "Value " + childMapForAttribs.get(c) + ": " + c.toString() + ", ";
}
if (children.size() > 0) s = s.substring(0, s.length() - 2);
} else {
s = s + "Class: " + classification;
}
return s + ")";
}
/**
* @return A list of rules encoding the decision tree below this node.
*/
public String buildRules() {
if (classification == null) {
LinkedList<String> li = buildRestRules();
String s = "";
for (String t : li) {
s = s + "if " + t + "\n";
}
return s;
} else return "Classify everything as " + classification;
}
private LinkedList<String> buildRestRules() {
LinkedList<String> li = new LinkedList<>();
if (classification == null) {
for (DecisionTreeNode c : children) {
Object v = childMapForAttribs.get(c);
String t = "Attr(" + attributeNr + ") = " + v;
LinkedList<String> sub = c.buildRestRules();
for (String s : sub) {
if (s.startsWith("then")) li.add(t + " " + s);
else li.add(t + " and " + s);
}
}
} else {
li.add("then classify as " + classification);
}
return li;
}
}
<file_sep>public class ClassifiedExample {
public DataExample example;
public String classification;
public ClassifiedExample(DataExample example, String classification) {
super();
this.example = example;
this.classification = classification;
}
public String toString() {
return example + " --> " + classification;
}
}
<file_sep>import java.util.HashSet;
import java.util.List;
public class DecisionTreeLearner {
/**
* Used to store all values of all attributes that the algorithm knows of.
*/
private static List<Object>[] attributeValues;
/**
* @param data Data that is used to build a decision tree.
* @return A tree that is able to categorize the given data.
*/
public static DecisionTreeNode ID3(DataExampleSet data) {
attributeValues = data.getAttributeValues();
HashSet<Integer> attribs = new HashSet<>();
for (int i = 0; i < data.getAttributeCount(); i++) attribs.add(i);
return ID3(null, data, attribs);
}
private static DecisionTreeNode ID3(DecisionTreeNode parent, DataExampleSet data, HashSet<Integer> attribs) {
//TODO: Implementieren Sie diese Methode!
}
}
| 39f10b534f8824ab7d272a6f53942aee588aad08 | [
"Java"
] | 3 | Java | T0biWan/MachineLearning | bc9a0603196e8d5c3774098e096b0a47cbfb958b | 22e627be850a486177a90afcb3978e2e5035c96a |
refs/heads/master | <repo_name>takecare/exercisio<file_sep>/app/src/main/java/io/exercis/ui/DummyFragment.kt
package io.exercis.ui
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import io.exercis.databinding.FragmentDummyBinding
const val ARG_PARAM = "param"
class DummyFragment : Fragment() {
companion object {
@JvmStatic
fun newInstance(param1: String) =
DummyFragment().apply {
arguments = Bundle().apply { putString(ARG_PARAM, param1) }
}
}
private var param: String? = null
private lateinit var binding: FragmentDummyBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let { param = it.getString(ARG_PARAM) }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDummyBinding.inflate(layoutInflater, container, false)
param?.let { binding.dummyText.text = it }
binding.dummyButton.setOnClickListener {
findNavController().navigate(Uri.parse("exercisio://fragment1"))
}
return binding.root;
}
}
class Fragment1 : Fragment() {
private lateinit var binding: FragmentDummyBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDummyBinding.inflate(layoutInflater, container, false)
binding.dummyText.text = "FRAGMENT _1_"
binding.dummyButton.setOnClickListener {
findNavController().navigate(Uri.parse("exercisio://fragment2"))
}
return binding.root;
}
}
class Fragment2 : Fragment() {
private lateinit var binding: FragmentDummyBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDummyBinding.inflate(layoutInflater, container, false)
binding.dummyText.text = "FRAGMENT _2_"
binding.dummyButton.setOnClickListener {
findNavController().navigate(Uri.parse("exercisio://exercises"))
}
return binding.root;
}
}
<file_sep>/config/dagger.gradle
apply plugin: 'kotlin-kapt'
//android {
// kapt {
// // https://kotlinlang.org/docs/reference/kapt.html#non-existent-type-correction
// correctErrorTypes true
// }
//}
dependencies {
def dagger_version = '2.27'
implementation "com.google.dagger:dagger:$dagger_version"
/*annotationProcessor*/ kapt "com.google.dagger:dagger-compiler:$dagger_version"
}
<file_sep>/README.md
### exercis.io
#### App structure
- Home (3 tabs)
-- Workouts: list of all stored/defined workouts
-- Home: details on last workout (e.g. date, duration)
-- Settings: app-wide settings
- Workout: name, sortable list of exercises that are part of this workout & button to add exercise
- Exercise: details about an exercise
- In-play: workout in play (details like timer, current exercise, next exercise, etc.)
##### Concerns
- Since we're gonna have the one activity approach, this means the home screen will consist of a
fragment that hosts the other 3 fragments (workouts, home and settings)
#### Module structure
Structure still under review.
- App: main module
- Workouts: list of workouts, creating a new workout flow (will probably depend on 'exercises')
- Exercises: exercise screen, new exercise flow
- Session: exercise session/in-play
- Settings: app-wide settings, including settings screen
#### Architecture and dependencies
Questions left to answer:
- MVVM vs MVI?
- RxJava, yes or no?
##### Dependencies
- ViewModel
- Room
- Dagger
- OkHttp
- Retrofit
<file_sep>/base/build.gradle
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply from: loadConfig('kotlin')
apply from: loadConfig('android')
apply from: loadConfig('dagger')
apply from: loadConfig('viewmodel')
apply from: loadConfig('networking')
<file_sep>/app/src/main/java/io/exercis/ui/MainFragment.kt
package io.exercis.ui
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.navigation.NavDeepLinkRequest
import androidx.navigation.NavDirections
import androidx.navigation.fragment.findNavController
import androidx.savedstate.SavedStateRegistryOwner
import io.exercis.R
import io.exercis.databinding.FragmentMainBinding
class MainViewModelFactory(
owner: SavedStateRegistryOwner,
defaultArgs: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
return if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
MainViewModel()
} else {
throw IllegalStateException("")
} as T
}
}
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
val viewModel: MainViewModel by viewModels { MainViewModelFactory(this) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainBinding.inflate(layoutInflater, container, false)
binding.mainButton.setOnClickListener {
findNavController().navigate(R.id.action_main_to_another)
}
binding.exercisesButton.setOnClickListener {
findNavController().navigate(Uri.parse("exercisio://exercises"))
}
binding.workoutsButton.setOnClickListener {
findNavController().navigate(Uri.parse("exercisio://workouts"))
}
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// TODO: Use the ViewModel
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/domain/ExercisesRepository.kt
package io.exercis.exercises.domain
import kotlinx.coroutines.flow.Flow
interface ExercisesRepository {
suspend fun getExercises(): Flow<Exercise>
suspend fun addExercise(workout: Exercise)
}
<file_sep>/base/src/main/java/io/exercis/base/NetworkModule.kt
package io.exercis.base
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import javax.inject.Singleton
@Module
class NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
// TODO add interceptors, etc.
.build()
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/domain/Exercise.kt
package io.exercis.exercises.domain
data class Exercise(
val name: String,
val description: String
)
<file_sep>/base/src/main/java/io/exercis/base/ui/BaseViewModel.kt
package io.exercis.base.ui
import androidx.lifecycle.*
import io.exercis.base.di.ViewModelAssistedFactory
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
// TODO merge Effect and State? e.g. Pair<State, Effect> and effect has a 'consumed' bool
interface State
interface Effect
interface Event
abstract class BaseViewModel<S : State, E : Effect, Ev : Event>(
private val initialState: S,
private val handle: SavedStateHandle
) : ViewModel() {
private val _state = MutableLiveData<S>().apply {
postValue(initialState)
}
val state: LiveData<S> get() = _state
protected val currentState: S? get() = _state.value
fun observeState(owner: LifecycleOwner, observer: Observer<S>) {
_state.observe(owner, observer)
}
// https://github.com/android/architecture-samples/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java
private val _effects = MutableLiveData<E>()
val effects: LiveData<E> get() = _effects
fun observeEffects(owner: LifecycleOwner, observer: Observer<E>) {
_effects.observe(owner, observer)
}
fun observe(events: BroadcastChannel<Ev>) {
observe(events.asFlow())
}
fun observe(events: Flow<Ev>) { // rename to bind()? connect()?
viewModelScope.launch {
events.collect { handleEvent(it) }
}
}
fun emit(state: S?) {
state?.let { _state.postValue(it) }
}
fun emit(effect: E?) {
effect?.let { _effects.postValue(it) }
}
abstract fun handleEvent(event: Ev)
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/domain/model/Workout.kt
package io.exercis.workouts.domain.model
import io.exercis.exercises.domain.Exercise
import java.time.Duration
data class WorkoutExercise(
val exercise: Exercise,
val duration: Duration
// # of series? # of reps per series?
)
data class Workout(
val name: String,
val description: String?,
val exercises: List<WorkoutExercise>
)
<file_sep>/exercises/src/main/java/io/exercis/exercises/ui/ExerciseViewModel.kt
package io.exercis.exercises.ui
import androidx.lifecycle.SavedStateHandle
import io.exercis.base.ui.BaseViewModel
import io.exercis.base.ui.Effect
import io.exercis.base.ui.Event
import io.exercis.base.ui.State
import io.exercis.exercises.domain.Exercise
class ExerciseViewModel constructor(
// private val getWorkouts: GetWorkoutsUseCase,
handle: SavedStateHandle
) : BaseViewModel<ExercisesState, ExercisesEffect, ExercisesEvent>(
ExercisesState(isLoading = true),
handle
) {
override fun handleEvent(event: ExercisesEvent) {
when (event) {
is ExercisesEvent.Displayed -> {
//
}
is ExercisesEvent.ExerciseClicked -> {
//
}
}
}
private suspend fun loadData() {
emit(currentState?.copy(isLoading = true))
val exercises = emptyList<Exercise>()
emit(
currentState?.copy(
isLoading = false,
data = exercises
)
)
}
}
sealed class ExercisesEvent : Event {
object Displayed : ExercisesEvent()
data class ExerciseClicked(val exercise: Exercise) : ExercisesEvent()
}
sealed class ExercisesEffect : Effect {
// for toasts, navigation, etc. (pushed from view model to view)
data class Toast(val message: String) : ExercisesEffect()
}
data class ExercisesState(
val isLoading: Boolean = false,
val hasError: Boolean = false,
val data: List<Exercise>? = null
) : State {
val hasData: Boolean get() = data != null
}
<file_sep>/config/view-binding.gradle
android {
viewBinding {
enabled = true
}
}
<file_sep>/app/src/main/java/io/exercis/ExecisioApplication.kt
package io.exercis
import android.app.Application
import io.exercis.exercises.ExercisesComponentProvider
import io.exercis.workouts.WorkoutsComponentProvider
class ExecisioApplication : Application(), WorkoutsComponentProvider,
ExercisesComponentProvider {
lateinit var applicationComponent: AppComponent
override fun onCreate() {
super.onCreate()
applicationComponent = DaggerAppComponent.builder()
.build()
}
override fun provideWorkoutsComponent() =
applicationComponent.workoutsComponentFactory().create()
override fun provideExercisesComponent() =
applicationComponent.exercisesComponentFactory().create()
}
<file_sep>/app/src/main/java/io/exercis/AppComponent.kt
package io.exercis
import dagger.Component
import dagger.Module
import io.exercis.base.NetworkModule
import io.exercis.exercises.ExercisesComponent
import io.exercis.workouts.WorkoutsComponent
import javax.inject.Singleton
@Singleton
@Component(modules = [NetworkModule::class, SubcomponentsModule::class])
interface AppComponent {
fun workoutsComponentFactory(): WorkoutsComponent.Factory
fun exercisesComponentFactory(): ExercisesComponent.Factory
// fun injectIntoMainActivity(activity: MainActivity)
}
@Module(subcomponents = [WorkoutsComponent::class, ExercisesComponent::class])
class SubcomponentsModule {}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutDetailViewModel.kt
package io.exercis.workouts.ui
import androidx.lifecycle.SavedStateHandle
import io.exercis.base.ui.BaseViewModel
import io.exercis.base.ui.Effect
import io.exercis.base.ui.Event
import io.exercis.base.ui.State
import io.exercis.exercises.domain.Exercise
import io.exercis.workouts.domain.model.Workout
class WorkoutDetailViewModel(
handle: SavedStateHandle
) : BaseViewModel<WorkoutDetailsState, WorkoutDetailsEffect, WorkoutDetailsEvent>(
WorkoutDetailsState(isLoading = true),
handle
) {
override fun handleEvent(event: WorkoutDetailsEvent) {
// TODO: handleEvent not implemented
}
}
sealed class WorkoutDetailsEvent : Event {
object Displayed : WorkoutDetailsEvent()
data class ExerciseClicked(val exercise: Exercise) : WorkoutDetailsEvent()
}
sealed class WorkoutDetailsEffect : Effect {
// for toasts, navigation, etc. (pushed from view model to view)
data class NavigateToExercise(val exercise: Exercise) : WorkoutDetailsEffect()
}
data class WorkoutDetailsState(
val isLoading: Boolean = false,
val hasError: Boolean = false,
val data: List<Workout>? = null
) : State {
val hasData: Boolean get() = data != null
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/ExercisesComponent.kt
package io.exercis.exercises
import dagger.Subcomponent
import io.exercis.base.di.FragmentScope
import io.exercis.exercises.domain.DomainModule
import io.exercis.exercises.ui.ExercisesFragment
@FragmentScope
@Subcomponent(modules = [DomainModule::class])
interface ExercisesComponent {
@Subcomponent.Factory
interface Factory {
fun create(): ExercisesComponent
}
fun inject(fragment: ExercisesFragment)
}
interface ExercisesComponentProvider {
fun provideExercisesComponent(): ExercisesComponent
}
<file_sep>/config/kotlin.gradle
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/WorkoutsComponent.kt
package io.exercis.workouts
import dagger.Subcomponent
import io.exercis.base.di.FragmentScope
import io.exercis.workouts.domain.DomainModule
import io.exercis.workouts.ui.PresentationModule
import io.exercis.workouts.ui.WorkoutDetailsFragment
import io.exercis.workouts.ui.WorkoutsFragment
@FragmentScope
@Subcomponent(modules = [DomainModule::class, PresentationModule::class])
interface WorkoutsComponent {
@Subcomponent.Factory
interface Factory {
fun create(): WorkoutsComponent
}
fun inject(fragment: WorkoutsFragment)
fun inject(fragment: WorkoutDetailsFragment)
}
interface WorkoutsComponentProvider {
fun provideWorkoutsComponent(): WorkoutsComponent
}
<file_sep>/base/src/main/java/io/exercis/base/ui/BaseFragment.kt
package io.exercis.base.ui
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.launch
// rename to EventfulFragment?
abstract class BaseFragment<E : Event> : Fragment() {
val events = BroadcastChannel<E>(1)
fun emit(event: E) = lifecycleScope.launch { events.send(event) }
@OptIn(ExperimentalCoroutinesApi::class)
fun emitWhenStarted(event: E) =
lifecycleScope.launchWhenStarted { events.send(event) }
fun View.clicksEmit(event: E) {
setOnClickListener { emit(event) }
}
}
@OptIn(ExperimentalCoroutinesApi::class)
fun <E : Event> BroadcastChannel<E>.emit(event: E, scope: CoroutineScope) =
scope.launch { send(event) }
<file_sep>/workouts/src/main/java/io/exercis/workouts/data/model/WorkoutDataModel.kt
package io.exercis.workouts.data.model
import io.exercis.exercises.data.model.ExerciseDataModel
data class WorkoutExerciseDataModel(
val exercise: ExerciseDataModel,
val duration: Int // mins
)
data class WorkoutDataModel(
val name: String,
val description: String? = null,
val exercises: List<WorkoutExerciseDataModel>
)
<file_sep>/exercises/src/main/java/io/exercis/exercises/data/DataModule.kt
package io.exercis.exercises.data
import dagger.Module
import dagger.Provides
import io.exercis.base.di.FragmentScope
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import javax.inject.Named
@Module
class DataModule {
@Provides
@FragmentScope
fun provideRetrofit(client: OkHttpClient): Retrofit {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(client)
.build()
return retrofit
}
@Provides
@Named("local") // TODO custom annotation
@FragmentScope
fun provideLocalDataSource() =
LocalExercisesDataSource()
@Provides
@Named("remote")
@FragmentScope
fun provideRemoteDataSource() =
NetworkExercisesDataSource()
}
<file_sep>/config/networking.gradle
dependencies {
api "com.squareup.okhttp3:okhttp:4.5.0"
api "com.squareup.retrofit2:retrofit:2.8.1"
}
<file_sep>/config/viewmodel.gradle
dependencies {
def livedata_version = '2.2.0-rc02'
def lifecycle_version = '2.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$livedata_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutsViewModelFactory.kt
package io.exercis.workouts.ui
import androidx.lifecycle.SavedStateHandle
import io.exercis.base.di.ViewModelAssistedFactory
import io.exercis.workouts.domain.GetWorkoutsUseCase
import javax.inject.Inject
class WorkoutsViewModelFactory @Inject constructor(
private val getWorkouts: GetWorkoutsUseCase
) : ViewModelAssistedFactory<WorkoutsViewModel> {
override fun create(handle: SavedStateHandle): WorkoutsViewModel {
return WorkoutsViewModel(getWorkouts, handle)
}
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/PresentationModule.kt
package io.exercis.workouts.ui
import dagger.Module
@Module
class PresentationModule {
// drop
}
<file_sep>/config/navigation.gradle
apply plugin: "androidx.navigation.safeargs.kotlin"
dependencies {
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
<file_sep>/config/room.gradle
apply plugin: 'kotlin-kapt'
dependencies {
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
// implementation "androidx.room:room-rxjava2:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/data/DummyData.kt
package io.exercis.workouts.data
import io.exercis.exercises.data.DummyData.Companion.exercises
import io.exercis.workouts.data.model.WorkoutDataModel
import io.exercis.workouts.data.model.WorkoutExerciseDataModel
class DummyData {
companion object {
val workoutExercises = exercises.mapIndexed { i, e -> WorkoutExerciseDataModel(e, i + 1) }
val workouts = (1 until workoutExercises.size).map {
WorkoutDataModel(
"workout $it",
"workout desc $it",
listOf(workoutExercises[it - 1], workoutExercises[it])
)
}
}
}
<file_sep>/config/test.gradle
dependencies {
testImplementation 'junit:junit:4.13'
}
<file_sep>/config/android-test.gradle
dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
testImplementation "androidx.arch.core:core-testing:2.1.0"
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutsFragment.kt
package io.exercis.workouts.ui
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.NavDeepLinkRequest
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.exercis.base.di.GenericSavedStateViewModelFactory
import io.exercis.base.ui.BaseFragment
import io.exercis.workouts.WorkoutsComponentProvider
import io.exercis.workouts.databinding.FragmentWorkoutsBinding
import io.exercis.workouts.databinding.RowWorkoutBinding
import io.exercis.workouts.domain.model.Workout
import javax.inject.Inject
// this fragment should be able to support:
// 1. empty list of workouts
// 2. list of workouts
// 3. create new workout
// 4. navigate to workout (list of exercises)
// 5. change workout details (eg. name) (still not sure about this one)
class WorkoutsFragment : BaseFragment<WorkoutsEvent>() {
private lateinit var binding: FragmentWorkoutsBinding
@Inject
lateinit var viewModelFactory: WorkoutsViewModelFactory
private val viewModel: WorkoutsViewModel by viewModels {
GenericSavedStateViewModelFactory(viewModelFactory, this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
(activity?.application as WorkoutsComponentProvider)
.provideWorkoutsComponent()
.inject(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentWorkoutsBinding.inflate(layoutInflater, container, false)
binding.workoutsButton.clicksEmit(WorkoutsEvent.Displayed)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
emitWhenStarted(WorkoutsEvent.Displayed) // is this really needed?
// expose flow of ui events to the view model
viewModel.observe(events)
// observe the state the view model outputs
viewModel.observeState(viewLifecycleOwner, Observer { state ->
when {
state.isLoading -> {
Toast.makeText(context, "loading", Toast.LENGTH_SHORT)
.show()
}
state.hasData -> {
val workouts = state?.data ?: emptyList()
with(binding.recyclerView) {
layoutManager = LinearLayoutManager(context)
adapter = WorkoutsRecyclerAdapter(workouts) {
emit(WorkoutsEvent.WorkoutClicked(it))
}
}
}
state.hasError -> {
Toast.makeText(context, "error", Toast.LENGTH_SHORT)
.show()
}
}
})
viewModel.observeEffects(viewLifecycleOwner, Observer { effect ->
when (effect) {
is WorkoutsEffect.Toast -> Toast.makeText(
context,
effect.message,
Toast.LENGTH_SHORT
)
.show()
is WorkoutsEffect.NavigateToWorkout -> {
val workout = effect.workout
// val request = NavDeepLinkRequest.Builder
// .fromUri()
findNavController().navigate(Uri.parse("exercisio://workout/${workout.name}"))
}
}
})
}
}
// https://developer.android.com/guide/topics/ui/layout/recyclerview
class WorkoutsViewHolder(
private val binding: RowWorkoutBinding,
private val listener: (Workout) -> Unit,
view: View
) : RecyclerView.ViewHolder(view) {
fun bind(workout: Workout) {
binding.mainText.text = workout.name
binding.secondaryText.text = workout.description
itemView.setOnClickListener { listener(workout) }
}
}
class WorkoutsRecyclerAdapter(private val listener: (Workout) -> Unit) :
RecyclerView.Adapter<WorkoutsViewHolder>() {
var data: List<Workout> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
constructor(data: List<Workout>, listener: (Workout) -> Unit) : this(listener) {
this.data = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkoutsViewHolder {
val binding = RowWorkoutBinding.inflate(LayoutInflater.from(parent.context))
return WorkoutsViewHolder(binding, listener, binding.root)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: WorkoutsViewHolder, position: Int) {
val workout = data[position]
holder.bind(workout)
}
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutsViewModel.kt
package io.exercis.workouts.ui
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import io.exercis.base.ui.BaseViewModel
import io.exercis.base.ui.Effect
import io.exercis.base.ui.Event
import io.exercis.base.ui.State
import io.exercis.workouts.domain.GetWorkoutsUseCase
import io.exercis.workouts.domain.model.Workout
import kotlinx.coroutines.launch
// https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54
// https://stackoverflow.com/questions/47515997/observing-livedata-from-viewmodel
// https://codelabs.developers.google.com/codelabs/advanced-kotlin-coroutines/index.html?index=..%2F..index#9
class WorkoutsViewModel constructor(
private val getWorkouts: GetWorkoutsUseCase,
handle: SavedStateHandle
) : BaseViewModel<WorkoutsState, WorkoutsEffect, WorkoutsEvent>(
WorkoutsState(isLoading = true),
handle
) {
private val workouts: MutableLiveData<Workout> = MutableLiveData()
override fun handleEvent(event: WorkoutsEvent) {
when (event) {
is WorkoutsEvent.WorkoutClicked -> {
emit(WorkoutsEffect.NavigateToWorkout(event.workout))
}
is WorkoutsEvent.Displayed -> viewModelScope.launch {
loadData()
}
else -> {
// unexpected
}
}
}
private suspend fun loadData() {
emit(currentState?.copy(isLoading = true))
// val state = getWorkouts
// ._execute()
// .map { workout ->
// val currentWorkouts = currentState?.data ?: emptyList()
// currentState?.copy(
// isLoading = false,
// data = currentWorkouts + workout
// )
// }
// .asLiveData()
val workouts = getWorkouts.execute()
emit(
currentState?.copy(
isLoading = false,
data = workouts
)
)
}
}
sealed class WorkoutsEvent : Event {
object Displayed : WorkoutsEvent()
data class WorkoutClicked(val workout: Workout) : WorkoutsEvent()
}
sealed class WorkoutsEffect : Effect {
// for toasts, navigation, etc. (pushed from view model to view)
data class NavigateToWorkout(val workout: Workout) : WorkoutsEffect()
data class Toast(val message: String) : WorkoutsEffect()
}
data class WorkoutsState(
val isLoading: Boolean = false,
val hasError: Boolean = false,
val data: List<Workout>? = null
) : State {
val hasData: Boolean get() = data != null
}
<file_sep>/settings/build.gradle
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply from: loadConfig('kotlin')
apply from: loadConfig('android')
apply from: loadConfig('viewmodel')
apply from: loadConfig('navigation')
apply from: loadConfig('room')
apply from: loadConfig('android-test')
apply from: loadConfig('test')
<file_sep>/config/signing.gradle
android {
// TODO signingConfigs { ... }
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/data/WorkoutsRepositoryImpl.kt
package io.exercis.workouts.data
import io.exercis.workouts.data.model.WorkoutDataModel
import io.exercis.workouts.domain.WorkoutsRepository
import io.exercis.workouts.domain.model.Workout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import javax.inject.Inject
// https://proandroiddev.com/kotlin-flow-on-android-quick-guide-76667e872166
// https://medium.com/androiddevelopers/rxjava-to-kotlin-coroutines-1204c896a700
// https://codelabs.developers.google.com/codelabs/advanced-kotlin-coroutines/#0
// using data sources this way (local and remote) implies usage of streams (i.e. reactive
// programming). this brings about a set of issues, namely correctly merging the two streams (local
// and remote)
interface WorkoutsDataSource {
//
suspend fun getData(): List<WorkoutDataModel>
}
class NetworkWorkoutsDataSource : WorkoutsDataSource {
// retrofit service as dependency here?
override suspend fun getData(): List<WorkoutDataModel> {
return coroutineScope {
delay(20L)
emptyList<WorkoutDataModel>()
}
}
}
class LocalWorkoutsDataSource : WorkoutsDataSource {
// db as dependency here? how?
override suspend fun getData(): List<WorkoutDataModel> {
return coroutineScope {
delay(100L)
DummyData.workouts
}
}
}
// our local db will act as a cache as offline-mode enabler. we'll need a way of maintaining
// consistency
internal class WorkoutsRepositoryImpl(
private val networkDataSource: WorkoutsDataSource,
private val localDataSource: WorkoutsDataSource,
private val mapper: Mapper
) : WorkoutsRepository {
@ExperimentalCoroutinesApi
override suspend fun getWorkouts(): Flow<Workout> {
val network = networkDataSource.getData().asFlow()
val local = localDataSource.getData().asFlow()
return merge(network, local)
.map { mapper(it) }
}
override suspend fun addWorkout(workout: Workout) {
//
}
}
//internal typealias Mapper = (data: WorkoutDataModel) -> Workout
/*internal*/ class Mapper @Inject constructor() {
operator fun invoke(data: WorkoutDataModel): Workout {
return Workout(data.name, data.description, emptyList())
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/data/ExercisesRepositoryImpl.kt
package io.exercis.exercises.data
import io.exercis.exercises.data.model.ExerciseDataModel
import io.exercis.exercises.domain.Exercise
import io.exercis.exercises.domain.ExercisesRepository
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import javax.inject.Inject
import javax.inject.Named
interface ExercisesDataSource {
//
suspend fun getData(): List<ExerciseDataModel>
}
class NetworkExercisesDataSource :
ExercisesDataSource {
//
override suspend fun getData(): List<ExerciseDataModel> {
return coroutineScope {
delay(200L)
emptyList<ExerciseDataModel>()
}
}
}
class LocalExercisesDataSource : ExercisesDataSource {
//
override suspend fun getData(): List<ExerciseDataModel> {
return coroutineScope {
delay(100L)
DummyData.exercises
}
}
}
class ExercisesRepositoryImpl @Inject constructor(
@Named("remote") private val networkSource: ExercisesDataSource,
@Named("local") private val localSource: ExercisesDataSource,
private val mapper: Mapper
) : ExercisesRepository {
override suspend fun getExercises(): Flow<Exercise> {
val network = networkSource.getData().asFlow()
val local = localSource.getData().asFlow()
return merge(network, local)
.map { mapper(it) }
}
override suspend fun addExercise(workout: Exercise) {
// TODO: addWorkout not implemented
}
}
class Mapper @Inject constructor() {
operator fun invoke(data: ExerciseDataModel): Exercise {
return Exercise(data.name, data.description)
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/ui/ExercisesFragment.kt
package io.exercis.exercises.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.navigation.fragment.findNavController
import io.exercis.base.ui.BaseFragment
import io.exercis.exercises.databinding.FragmentExercisesBinding
import io.exercis.exercises.ExercisesComponentProvider
// this fragment should be able to support:
// 1. empty list of exercises
// 2. list of exercises
// 3. add new exercise (to current workout)
class ExercisesFragment : BaseFragment<ExercisesEvent>() {
private lateinit var binding: FragmentExercisesBinding
override fun onAttach(context: Context) {
super.onAttach(context)
(activity?.application as ExercisesComponentProvider)
.provideExercisesComponent()
.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// findNavController().popBackStack()
// }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentExercisesBinding.inflate(layoutInflater, container, false)
// TODO setup emissions
return binding.root
}
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/domain/DomainModule.kt
package io.exercis.workouts.domain
import dagger.Module
import dagger.Provides
import io.exercis.base.di.ActivityScope
import io.exercis.base.di.FragmentScope
import io.exercis.workouts.data.DataModule
@Module(includes = [DataModule::class])
class DomainModule {
@Provides
@FragmentScope
fun provideUseCase(repository: WorkoutsRepository): GetWorkoutsUseCase { // TODO drop this
return GetWorkoutsUseCase(repository)
}
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/domain/WorkoutsRepository.kt
package io.exercis.workouts.domain
import io.exercis.workouts.domain.model.Workout
import kotlinx.coroutines.flow.Flow
interface WorkoutsRepository {
suspend fun getWorkouts(): Flow<Workout>
suspend fun addWorkout(workout: Workout)
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/data/DataModule.kt
package io.exercis.workouts.data
import dagger.Module
import dagger.Provides
import io.exercis.base.di.FragmentScope
import io.exercis.workouts.domain.WorkoutsRepository
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import javax.inject.Named
@Module
class DataModule {
@Provides
@FragmentScope
fun provideRetrofit(client: OkHttpClient): Retrofit {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(client)
.build()
return retrofit
}
@Provides
@FragmentScope
fun bindWorkoutsRepository(
@Named("remote") networkWorkoutsDataSource: WorkoutsDataSource,
@Named("local") localWorkoutsDataSource: WorkoutsDataSource,
mapper: Mapper
): WorkoutsRepository {
return WorkoutsRepositoryImpl(networkWorkoutsDataSource, localWorkoutsDataSource, mapper)
}
@Provides
@Named("local") // TODO custom annotation
@FragmentScope
fun provideLocalDataSource(): WorkoutsDataSource {
return LocalWorkoutsDataSource()
}
@Provides
@Named("remote")
@FragmentScope
fun provideRemoteDataSource(): WorkoutsDataSource {
return NetworkWorkoutsDataSource()
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/data/DummyData.kt
package io.exercis.exercises.data
import io.exercis.exercises.data.model.ExerciseDataModel
class DummyData {
companion object {
val exercises = (1..10).map {
ExerciseDataModel(
"exercise_data_model_$it",
"exercise $it",
"description $it"
)
}
}
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/domain/GetWorkoutsUseCase.kt
package io.exercis.workouts.domain
import io.exercis.workouts.domain.model.Workout
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.toList
import javax.inject.Inject
class GetWorkoutsUseCase @Inject constructor(private val workoutsRepository: WorkoutsRepository) {
suspend fun execute(): List<Workout> {
// TODO set dispatcher?
// we're emitting one by one and then collecting them to a list here but we're fine with
// that as we want to grasp flows first (and then we can drop these unnecessary operations)
return workoutsRepository.getWorkouts().toList()
}
suspend fun _execute(): Flow<Workout> {
// TODO set dispatcher?
return workoutsRepository.getWorkouts()
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/data/model/ExerciseDataModel.kt
package io.exercis.exercises.data.model
data class ExerciseDataModel(
val id: String, // UUID?
val name: String,
val description: String
)
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply from: loadConfig('kotlin')
apply from: loadConfig('android')
apply from: loadConfig('dagger')
apply from: loadConfig('viewmodel')
apply from: loadConfig('navigation')
apply from: loadConfig('android-test')
apply from: loadConfig('test')
apply from: loadConfig('signing')
// this needs to be here otherwise dagger cannot generate the app component
apply from: loadConfig('networking')
android {
defaultConfig {
applicationId "io.exercis"
}
buildTypes {
debug {
applicationIdSuffix '.debug'
debuggable true
}
}
}
dependencies {
implementation project(path: ':base')
implementation project(path: ':workouts')
implementation project(path: ':exercises')
// implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutDetailsViewModelFactory.kt
package io.exercis.workouts.ui
import androidx.lifecycle.SavedStateHandle
import io.exercis.base.di.ViewModelAssistedFactory
import javax.inject.Inject
// TODO can we use kotlin poet to generate this easily?
class WorkoutDetailsViewModelFactory @Inject constructor(
//
) : ViewModelAssistedFactory<WorkoutDetailViewModel> {
override fun create(handle: SavedStateHandle): WorkoutDetailViewModel {
return WorkoutDetailViewModel(handle)
}
}
<file_sep>/build.gradle
buildscript {
ext.kotlin_version = '1.3.72'
ext.nav_version = '2.3.0-alpha06'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jlleitschuh.gradle:ktlint-gradle:9.2.1"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
plugins {
id "io.gitlab.arturbosch.detekt" version "1.9.1"
}
allprojects {
repositories {
google()
jcenter()
}
}
apply from: loadConfig('static-analysis')
def loadConfig(configFile) {
return new File(file('config'), "${configFile}.gradle")
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/domain/GetExercisesUseCase.kt
package io.exercis.exercises.domain
class GetExercisesUseCase(
private val exercisesRepository: ExercisesRepository
) {
//
}
<file_sep>/settings.gradle
rootProject.name = 'exercisio'
include ':app'
include ':workouts'
include ':settings'
include ':inplay'
include ':exercises'
include ':base'
<file_sep>/config/static-analysis.gradle
subprojects {
apply plugin: "org.jlleitschuh.gradle.ktlint"
apply plugin: 'io.gitlab.arturbosch.detekt'
// https://detekt.github.io/detekt/
detekt {
toolVersion = "1.9.1"
config = files("../config/detekt/detekt.yml")
buildUponDefaultConfig = true
parallel = false
reports {
xml {
enabled = false
destination = file("path/to/destination.xml")
}
html {
enabled = true
destination = file("path/to/destination.html")
}
txt {
enabled = false
destination = file("path/to/destination.txt")
}
}
}
// https://github.com/jlleitschuh/ktlint-gradle
// https://github.com/pinterest/ktlint
ktlint {
version = "0.36.0"
android = true
ignoreFailures = false
verbose = false
disabledRules = ["no-wildcard-imports"]
}
}
<file_sep>/exercises/src/main/java/io/exercis/exercises/domain/DomainModule.kt
package io.exercis.exercises.domain
import dagger.Module
import io.exercis.exercises.data.DataModule
@Module(includes = [DataModule::class])
class DomainModule {
//
}
<file_sep>/workouts/src/main/java/io/exercis/workouts/ui/WorkoutDetailsFragment.kt
package io.exercis.workouts.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import io.exercis.base.di.GenericSavedStateViewModelFactory
import io.exercis.base.ui.BaseFragment
import io.exercis.workouts.WorkoutsComponentProvider
import io.exercis.workouts.databinding.FragmentWorkoutDetailsBinding
import javax.inject.Inject
class WorkoutDetailsFragment : BaseFragment<WorkoutDetailsEvent>() {
private lateinit var binding: FragmentWorkoutDetailsBinding
@Inject
lateinit var viewModelFactory: WorkoutDetailsViewModelFactory
private val workoutName: String?
get() = arguments?.getString("name")
private val viewModel: WorkoutDetailViewModel by viewModels {
GenericSavedStateViewModelFactory(viewModelFactory, this)
}
override fun onAttach(context: Context) {
super.onAttach(context)
(activity?.application as WorkoutsComponentProvider)
.provideWorkoutsComponent()
.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let { bundle -> bundle.keySet().forEach { println("$it: ${bundle[it]}") } }
// val action: String? = intent?.action
// val data: Uri? = intent?.data
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentWorkoutDetailsBinding.inflate(layoutInflater, container, false)
binding.workoutName.text = workoutName
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.observe(events)
viewModel.observeEffects(viewLifecycleOwner, Observer { effect ->
when (effect) {
is WorkoutDetailsEffect.NavigateToExercise -> {
// TODO
}
}
})
}
}
| c9ceb919eabebcb0aa020368fa526ab32a6be7fa | [
"Markdown",
"Kotlin",
"Gradle"
] | 51 | Kotlin | takecare/exercisio | 1c7f973dfe227f56085bcbe8d755ef1f5df1497a | 369a627dc0b5be72ef34421918bf96db3df9ab14 |
refs/heads/master | <file_sep>package ch.supsi.dti.isin.meteoapp.fragments;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
;
import android.net.Uri;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import ch.supsi.dti.isin.meteoapp.R;
import ch.supsi.dti.isin.meteoapp.activities.MainActivity;
import ch.supsi.dti.isin.meteoapp.model.LocationsHolder;
import ch.supsi.dti.isin.meteoapp.model.apirequest.Location;
import ch.supsi.dti.isin.meteoapp.model.apirequest.WeatherHttpClient;
import ch.supsi.dti.isin.meteoapp.model.apirequest.CurrentWeather;
public class DetailLocationFragment extends Fragment implements Updateable{
private static final String ARG_LOCATION_ID = "location_id";
private Location mLocation;
private TextView mLocationName;
private TextView mWeatherType;
private TextView mTemp;
private TextView mTempMin;
private TextView mTempMax;
private ImageView mImageView;
public static DetailLocationFragment newInstance(UUID locationId) {
Bundle args = new Bundle();
args.putSerializable(ARG_LOCATION_ID, locationId);
DetailLocationFragment fragment = new DetailLocationFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID locationId = (UUID) getArguments().getSerializable(ARG_LOCATION_ID);
mLocation = LocationsHolder.get(getActivity()).getLocation(locationId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_detail_location, container, false);
mLocationName = v.findViewById(R.id.locationName);
mWeatherType = v.findViewById(R.id.weatherType);
mTemp = v.findViewById(R.id.temp);
mTempMin = v.findViewById(R.id.tempMin);
mTempMax = v.findViewById(R.id.tempMax);
mImageView = v.findViewById(R.id.imageView);
WeatherHttpClient w = new WeatherHttpClient(this);
if(mLocation.getName().equals("My position")){
w.getCurrentWeatherDataByLatLon(
MainActivity.currentLocation.getCoord().getLat(),
MainActivity.currentLocation.getCoord().getLon()
);
} else {
w.getCurrentWeatherDataByLocation(mLocation);
}
return v;
}
public void update(CurrentWeather cw){
if(cw == null)
return;
mLocationName.setText(cw.getName());
mWeatherType.setText(cw.getWeather().get(0).getDescription());
mTemp.setText((int) cw.getMain().getTemp() + "°C");
mTempMin.setText((int) cw.getMain().getTemp_min() + "°C");
mTempMax.setText((int) cw.getMain().getTemp_max() + "°C");
String mDrawableName = "a" + cw.getWeather().get(0).getIcon();
int resID = getResources().getIdentifier(mDrawableName, "drawable", getContext().getPackageName());
mImageView.setImageResource(resID);
}
}
| 806724a374973ef496d46c55ef50f452f593ee66 | [
"Java"
] | 1 | Java | pavodev/AppMeteo | 305c914645b1731ce1b5dbe37695537e2db719bd | 1d8b84a9624eae39a9b3ab41129916fd8021960a |
refs/heads/master | <file_sep>const express = require('express');
var server = express();
// server.use('/b.html',(req, res)=>{
// res.writeHead(200,{
// "Content-Type":"text/plain;charset=utf-8"
// });
// res.write('b哈哈哈哈哈哈哈');
// res.end();
// })
// server.use('/a.html',(req, res)=>{
// // res.writeHead(200,{
// // "Content-Type":"text/plain;charset=utf-8"
// // });
// res.send({a:12,b:15}); // send 方法添加了可以直接发送对象
// res.end();
// })
server.get('/',function(req,res){
res.write("GET"+req.url);
res.end();
})
server.post('/',function(req,res){
res.write("POST"+req.url);
res.end();
})
server.listen(8080);<file_sep>var fs = require('fs');
fs.writeFile('2.txt','测试写入文件222',function (err){
if (err){
console.log('写入失败');
}
})
// wrireFile(文件名,内容,回调) // 多次写入会覆盖。。。<file_sep>const http = require('http');
const url = require('url') // url处理参数
http.createServer((req,res)=>{
let obj = url.parse(req.url,true);
console.log(obj.pathname,obj.query)
res.write('love xiao miao')
res.end();
}).listen(8080);<file_sep>const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const url = require('url');
var user= {};
http.createServer((req,res)=>{
// GET
res.writeHead(200,{
"Content-Type":"text/plain;charset=utf-8"
});
let obj = url.parse(req.url,true);
let path = obj.pathname;
let param = obj.query;
// 区分访问文件还是文件
var str = '';
req.on('data',(data)=>{
str+=data;
})
req.on('end',()=>{
const POST = querystring.parse(str);
console.log(path,param,POST,str)
var file_name = './www'+path;
if (path=='/user'){ // 接口的访问
switch(POST.act){
case 'reg':
if(user[POST.user]){
res.write(`{'ok':false,msg:'用户已存在'}`)
}else {
user[POST.user]=POST.pass;
res.write(`{
'ok':true,msg:'注册成功'
}`)
}
break;
case 'login':
if (user[POST.user]==null){
res.write(`{
'ok':false,msg:'用户不存在'
}`)
} else if(user[POST.user] !== POST.pass){
res.write(`{
'ok':false,msg:'用户名或密码错误'
}`)
} else {
res.write(`{
'ok':true,msg:'登陆成功'
}`)
}
break;
default:
res.write(`{
'ok':false,msg:'未知动作'
}`)
}
res.end();
}else {
fs.readFile(file_name,(err,data)=>{
if(err){
res.write('NOT FOUND');
} else{
res.write(data);
}
res.end();
})
}
})
}).listen(8080);<file_sep>const express = require('express');
const bodyParser = require('body-parser');// 文件上传它处理不了
const multer =require('multer');
const pathlib = require('path');
const fs = require('fs');
var server = express();
var objmulter=multer({dest:'./www/upload'}); // 上传保存路径
// server.use(bodyParser.urlencoded({extended:false}));
server.use(objmulter.any());
server.post('/',(req,res)=>{
console.log(req.files); // 读取上传文件
// 获取原始扩展名
// var newName=req.files[0].path+pathlib.parse(req.files[0].originalname).ext;
var newName=req.files[0].destination+'/'+req.files[0].originalname;
fs.rename(req.files[0].path,newName,(err)=>{
if(err){
res.send('上传失败')
}else{
res.send('上传成功')
}
})
})
server.listen(8080)<file_sep>const express = require('express');
const cookieParser = require('cookie-parser'); // session 需要cookie
const cookieSession = require('cookie-session');
var server = express();
// cookie
server.use(cookieParser());
server.use(cookieSession({
keys:['www','eeeee','tyyyy'], // session 秘钥
name:'wangdong',
maxAge:2*3600*1000// 有效期
}));
server.use('/',(req,res)=>{ // cookie 加密
if (req.session['count']== null){
req.session['count'] = 1;
}else {
req.session['count']++;
}
console.log(req.session);
delete req.session // 删除session
res.send('OK');
})
server.listen(8080);<file_sep>const ejs = require('ejs');
var str = ejs.renderFile('./views/2.ejs',{name:'王冬冬'},(err, data)=>{
if(err){
console.log('编译失败');
}else{
console.log(data)
}
});
console.log(str);<file_sep>const querystring = require('querystring')
var json = querystring.parse('user=wangdongdong&pass=<PASSWORD>&age=25');
console.log(json);<file_sep>const mod1 = require('./mod'); //自己的模块 加路径 .JS可以省略 自定义模块放在moudle里可以不写 ./
console.log(mod1.a,mod1.b);<file_sep>const http = require("http");
const fs = require("fs");
http.createServer((req,res)=>{
var name = './www'+req.url;
console.log(req.url,222)
fs.readFile(name,(err,data)=>{
if(err){
res.write('error')
}else{
res.write(data)
res.end();
}
})
}).listen(8080)<file_sep>1、下载mysql模块(client) npm install mysql
2、连接
var db = mysql.createConnection({host, port, user, password,database});
3、查询
db.query(SQL, (err, data)=>{})
4、SQL语句
关键字大写
增删改查
INSERT INTO 表 (字段列表) VALUES(值列表)
INSERT INTO users(`ID`,`username`,`password`) VALUES(0,'<PASSWORD>','<PASSWORD>')
SELECT 什么 FROM 表
SELECT * FROM `users`<file_sep>var express = require("express");
var request = require("request");
const mysql = require('mysql')
// 代理
var app = express();
app.get("/api",(req,res)=>{
var db =mysql.createConnection({host: 'localhost',user:'root',password:'<PASSWORD>',database:'blog'});
db.query('SELECT * FROM `banner_table`;',(err,data)=>{
if(err){
res.status(500).send('database error').end();
}else {
res.setHeader("Cache-Control", "no-store");
let obj = {success:true};
obj.data = data;
console.log(data)
res.status(200).send(obj);
// res.render('index.ejs', {banners: data})
}
})
// res.send({ success:'yes',data:"444444"})
})
app.listen(3000)<file_sep>const jade = require('jade');
const fs= require('fs');
// var str = jade.renderFile('./views/1.jade',{pretty:true});
var str = jade.renderFile('./views/11.jade',{pretty:true});
console.log(str);
fs.writeFile('./build/2.html',str,(err,data)=>{
if(err){
console.log('写入失败')
}else{
console.log('写入成功')
}
})<file_sep>const express = require('express');
const static = require('express-static');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const bodyParser = require('body-parser');// 只能解析数据类 的post
const multer = require('multer'); // 解析文件上传
const ejs = require('ejs');
const consolidate = require('consolidate');
const mysql = require('mysql');
var server = express();
server.listen(8080)
server.use(cookieParser('wthguihh'));
var arr = [];
for(var i = 0;i<1000000;i++){
arr.push("keys"+Math.random());
}
server.use(cookieSession({name:'user',keys:arr,maxAge:20*3600*1000}));
server.use(bodyParser.urlencoded({extended:false}));
server.use(multer({dest:'./www/upload'}).any())
server.engine('html',consolidate.ejs)
server.set('views','./views')
server.set('view engine','html');
server.get('/',(req,res)=>{
var db =mysql.createConnection({host: 'localhost',user:'root',password:'<PASSWORD>',database:'blog'});
db.query('SELECT * FROM `banner_table`;',(err,data)=>{
if(err){
res.status(500).send('database error').end();
}else {
console.log(data)
res.render('index.ejs', {banners: data})
}
})
})
server.use(static('./www'))<file_sep>const http = require('http');
http.createServer((req,res)=>{
var str='';
var i = 0;
req.on('data',function (data){
console.log(`第${i++}次发送数据`);
str+= data;
})
req.on('end',function(){
//console.log(str)
res.write('SUCCESS!!!')
res.end();
})
}).listen(8080);<file_sep>// require 引入模块
// exports 输出一个
// moudle mo模块 批量输出
// exports.a = 12;
// exports.b= 1244;
// exports.c = 12;
// exports.d= 1244;
module.exports={
a:12,
b:5556
}<file_sep>const http = require('http');
const querystring = require('querystring')
http.createServer((req,res)=>{
let param ={};
if (req.url.indexOf('?') !== -1){
let params = req.url.split('?');
let url = params[1];
param = querystring.parse(url);
} else {
console.log(res.url)
}
console.log(param);
res.write('love xiao miao')
res.end();
}).listen(8080);<file_sep>const express = require('express');
var server = express();
server.use('/b.html',(req, res)=>{
res.writeHead(200,{
"Content-Type":"text/plain;charset=utf-8"
});
res.write('b哈哈哈哈哈哈哈');
res.end();
})
server.use('/a.html',(req, res)=>{
console.log(3333);
// res.writeHead(200,{
// "Content-Type":"text/plain;charset=utf-8"
// });
res.send([{
id: '12987122',
name: '好滋好味鸡蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷兰优质淡奶,奶香浓而不腻',
address: '上海市普陀区真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987123',
name: '好滋好味鸡蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷兰优质淡奶,奶香浓而不腻',
address: '上海市普陀区真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987125',
name: '好滋好味鸡蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷兰优质淡奶,奶香浓而不腻',
address: '上海市普陀区真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}, {
id: '12987126',
name: '好滋好味鸡蛋仔',
category: '江浙小吃、小吃零食',
desc: '荷兰优质淡奶,奶香浓而不腻',
address: '上海市普陀区真北路',
shop: '王小虎夫妻店',
shopId: '10333'
}]); // send 方法添加了可以直接发送对象
res.end();
})
server.listen(8090);<file_sep>const express= require('express');
var server = express();
// 目录1:/user/
var routeUser = express.Router();
routeUser.get('/1.html',(req,res)=>{
res.send('user1');
})
routeUser.get('/2.html',(req,res)=>{
res.send('user2');
})
server.use('/user',routeUser)
var articleUser = express.Router();
articleUser.get('/1.html',(req,res)=>{
res.send('1111111');
})
articleUser.get('/2.html',(req,res)=>{
res.send('2222222');
})
server.use('/article',articleUser)
server.listen(8080)
<file_sep>setInterval((req,res)=>{
console.log(Math.random())
},1000)<file_sep>const express = require('express')
const consolidate = require('consolidate');
const multer =require('multer');
const pathlib = require('path');
const ejs = require('ejs')
const fs = require('fs')
var server = express();
server.listen(8080);
server.engine('html',consolidate.ejs) // 模板引擎 1、什么模板引擎
server.set('views','./www') // 文件模板中在哪
server.set('view engine','html');
server.get('/index.html',(req, res)=>{
res.render('index.ejs', {name:'王冬冬'})
})
server.get('/1.txt',(req,res)=>{
res.setHeader('Content-Disposition','attachment;filename=1.txt');
res.sendFile('/Users/dongdongwang/demo/nodep/download/www/download/崔天琪 - 放过.mp3')
})
var objmulter=multer({dest:'./www/upload'}); // 上传保存路径
// server.use(bodyParser.urlencoded({extended:false}));
server.use(objmulter.any());
server.post('/upload',(req,res)=>{
console.log(req.files); // 读取上传文件
// 获取原始扩展名
// var newName=req.files[0].path+pathlib.parse(req.files[0].originalname).ext;
var newName=req.files[0].destination+'/'+req.files[0].originalname;
fs.rename(req.files[0].path,newName,(err)=>{
if(err){
res.send('上传失败')
}else{
res.send('上传成功')
}
})
})
server.use(express.static('./www'))<file_sep>const express = require('express');
// const expresstatic = require('express-static');
const bodyParser = require('body-parser');
var server = express();
server.listen(8080);
// server.use(expresstatic('./www'));
// server.use(bodyParser.urlencoded({ // 用于给post封装body
// extended: true, //扩展模式
// limit: 2*1024*1024 // 限制-2M
// }));
server.use('/',(req,res,next)=>{
console.log('a');
next();
})
server.use('/',(req,res,next)=>{
console.log('b');
})
// res.query(); // GET
// res.body(); // POST | ae9278a1d19af69e73b4c591a84d0147bd90317c | [
"JavaScript",
"Text"
] | 22 | JavaScript | 8023wdlove/nodepractice | 5243956f3d96c729de6a9dda6fb6b702afa273dd | d25dadddb0f64b1b8827afdc2bff4f1ca1cf4178 |
refs/heads/master | <repo_name>evn88/voel<file_sep>/steps.js
var i = 2;
$("#addStep").on("click", function () {
if (i < 2) {
i = 2;
}
$('#steps').append($('#step').html()).attr('id', 'newStep' + i);
//$("#step").clone().attr('id', 'newStep' + i).fadeIn('slow').appendTo("#steps");
$("#newStep" + i + " div h5").html("Этап № " + i);
$("#newStep" + i + " input[name=startStepPlanning]").attr('name', 'startStepPlanning' + i);
$("#newStep" + i + " label[for=startStepPlanning]").attr('for', 'startStepPlanning' + i);
$("#newStep" + i + " input[name=stopStepPlanning]").attr('name', 'stopStepPlanning' + i);
$("#newStep" + i + " label[for=stopStepPlanning]").attr('for', 'stopStepPlanning' + i);
$("#newStep" + i + " input[name=startStepWorking]").attr('name', 'startStepWorking' + i);
$("#newStep" + i + " label[for=startStepWorking]").attr('for', 'startStepWorking' + i);
$("#newStep" + i + " input[name=stopStepWorking]").attr('name', 'stopStepWorking' + i);
$("#newStep" + i + " label[for=stopStepWorking]").attr('for', 'stopStepWorking' + i);
i++;
});
$("#delStep").on("click", function () {
i--;
$("#newStep" + i).detach();
});
<file_sep>/main.js
test
$(document).ready(function () {
//получаем массив с идентификаторами DCID_OBJID_DEVID_JOINID
var obj = jQuery.parseJSON('<?php echo $json; ?>');
for (var p in obj) {
//далее в цикле вытаскиваем данные Ajax запросом и подставляем
//их в таблицу идентификатором служит DCID_OBJID_DEVID_JOINID
var id = obj[p];
$.ajax({
type: "POST",
url: "app/ajax/mini_graf.php",
data: "id=" + obj[p],
success: function (msg) {
$("#" + obj[p]).html(msg).peity("bar", {
width: 150,
height: 30
});
$(".line").peity("line");
console.log(msg);
}
});
//console.log(obj[p]);
}
});
| f05cb2a0e50a880df315b178641f42b9f97843bd | [
"JavaScript"
] | 2 | JavaScript | evn88/voel | e50c6030650f64db5772723ac60003ce57949978 | 8e444f073b0c278230c243dd96d8f589c79d3b7c |
refs/heads/master | <file_sep><?php
declare(strict_types=1);
namespace Diduhless\NoFall;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\Listener;
use pocketmine\plugin\PluginBase;
class NoFall extends PluginBase implements Listener {
public function onEnable() {
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->getLogger()->info("§8[§eNoFall§8] NoFall has been enabled!");
}
/**
* @param EntityDamageEvent $event
*/
public function onDamage(EntityDamageEvent $event): void {
if($event->getCause() === EntityDamageEvent::CAUSE_FALL) {
$event->setCancelled();
}
}
} | ed07a5c355482b6ff9280130a14e2c97f5795f8d | [
"PHP"
] | 1 | PHP | didacdelolmo/NoFall | 1ea17e5723ba4f99551e739aa742251f51dbe578 | aebb99c5847b49d2a829f46782e56068029f1d71 |
refs/heads/master | <file_sep># ProjectRealwrold
try to copy this site with angular https://angular.realworld.io/<file_sep>import { Component, OnInit ,Input, Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-childcomponent1',
// templateUrl: './childcomponent1.component.html',
template:`
{{"Hello"+parentData}}
<button (click)="fireEvent()">fire event</button>
`,
styleUrls: ['./childcomponent1.component.css']
})
export class Childcomponent1Component implements OnInit {
@Input() public parentData;
@Output() public childEvent = new EventEmitter();
constructor() { }
ngOnInit() {
}
fireEvent(){
this.childEvent.emit("this is child event");
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ParamMap } from '@angular/router';
@Component({
selector: 'app-departments',
// templateUrl: './departments.component.html',
template:`
<ul>
<li [class.selected]="isSelected(department)" (click)="onSelect(department)" *ngFor="let department of departments">
{{department.id}}
</li>
</ul>
`,
styleUrls: ['./departments.component.css']
})
export class DepartmentsComponent implements OnInit {
constructor(private avRouter:ActivatedRoute , private router:Router) { }
departments = [
{id:1,name:"Math"},
{id:2,name:"Language"},
{id:3,name:"History"},
]
public selectedId;
ngOnInit() {
this.avRouter.paramMap.subscribe((params:ParamMap)=>{
let id = parseInt(params.get("id"));
this.selectedId = id;
})
}
onSelect(department){
this.router.navigate([department.id], {relativeTo:this.avRouter});
// this.router.navigate([{department.id}]);
}
isSelected(department){
return department.id === this.selectedId;
}
}
<file_sep>
import { Component, OnInit } from '@angular/core';
import {EmployeeService} from './employee.service'
@Component({
selector: 'app-root',
// templateUrl: './app.component.html',
// event binding
// template:`
// <input type="text" #myInput value="">
// <button (click)="log1(myInput.value)" >LogIt</button>
// `,
// two way binding
// template:`
// <input [(ngModel)]="name" />
// {{name}}
// `,
// *ngIf
// template:`
// <h2 *ngIf="displayFlag">Shikaiwen</h2>
// `,
// *ngIf
// template:`
// <h2 *ngIf="displayFlag"></h2>
// <div *ngIf="displayFlag; then thenBlock; else elseBlock"></div>
// <ng-template #thenBlock>
// <h2>Codevolution</h2>
// </ng-template>
// <ng-template #elseBlock>
// <h2>Name is Hidden</h2>
// </ng-template>
// `,
// ngSwitch directive
// template:`
// <div [ngSwitch]="color">
// <div *ngSwitchCase="'red'"> red is picked </div>
// <div *ngSwitchCase="'green'"> red is pigreencked </div>
// <div *ngSwitchCase="'yellow'"> red is yellow </div>
// <div *ngSwitchDefault> this default color </div>
// </div>
// `,
// for directive
template:`
<ul>
<li *ngFor="let employee of employeeList"> {{employee.id}} </li>
</ul>
`,
// @input to childcomponent1
// template:`
// <app-childcomponent1 [parentData]="datastr">
// </app-childcomponent1>
// `,
// @Output from childcomponent1
// template:`
// <app-childcomponent1 (childEvent)="message=$event" >
// </app-childcomponent1>
// {{message}}
// `,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'basic';
color = "red";
colors = ["red","orange","black","pink"]
employeeService= null;
constructor(private eService:EmployeeService){
// this.employeeService = eService;
}
displayFlag = true;
name = "";
datastr = "this is a string from app component";
public message = "";
public employeeList = [];
ngOnInit(): void {
// throw new Error("Method not implemented.");
// this.employeeList = this.eService.getEmployees();
this.eService.getEmployees().subscribe(data => this.employeeList = data);
}
log1(value){
console.log(value)
}
greet(){
console.log("hello")
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DepartmentsComponent } from './departments/departments.component';
import { EmployeesComponent } from './employees/employees.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { DepartmentDetailComponent } from './department-detail/department-detail.component';
import { DepartmentOverviewComponent } from './department-overview/department-overview.component';
import { DepartmentContactComponent } from './department-contact/department-contact.component';
const routes: Routes = [
{path:'', redirectTo:'/departments', pathMatch: 'full'},
{path:'departments', component: DepartmentsComponent},
{
path:'departments/:id',
component: DepartmentDetailComponent,
children:[
{path: 'overview',component: DepartmentOverviewComponent},
{path: 'contact',component: DepartmentContactComponent}
]
},
{path:'employee', component: EmployeesComponent},
{path:'**', component: PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [
DepartmentsComponent,
EmployeesComponent,
DepartmentDetailComponent,
DepartmentOverviewComponent,
DepartmentContactComponent
];<file_sep># angular6_learn
routing:
ng g c department-overview -it -is
online vscode editor
https://stackblitz.com/angular/pyypjgaxjrl<file_sep>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder,Validators } from '@angular/forms';
import { forbiddenNameValidator } from './username-validator';
@Component({
selector: 'app-react',
templateUrl: './react.component.html',
styleUrls: ['./react.component.css']
})
export class ReactComponent implements OnInit {
constructor(private fb:FormBuilder) { }
// registrationForm = new FormGroup({
// userName: new FormControl("keivn"),
// password: new FormControl(""),
// confirmPassword: new FormControl("")
// });
registrationForm = this.fb.group({
userName:["Vish",[Validators.required,Validators.minLength(3)]],
password:["<PASSWORD>",[forbiddenNameValidator]],
confirmPassword:["<PASSWORD>"],
})
userElt:FormControl = null;
ngOnInit() {
// this.registrationForm.setValue(new FormGroup({
// userName: new FormControl("keivn"),
// password: new FormControl(""),
// confirmPassword: new FormControl("")
// }));
this.registrationForm.patchValue(new FormGroup({
userName: new FormControl("keivn"),
password: new FormControl(""),
confirmPassword: new FormControl("")
}));
let userElt = this.registrationForm.get("userName");
userElt.
}
}
| f91db8ea71d336a11faea0d85b9798deec331a9e | [
"Markdown",
"TypeScript"
] | 7 | Markdown | shikaiwen/angular6_learn | 54c6b4976f02e9f128e6673bb0c81b7af2699f03 | aec99165b8d5a4fbfc3d8165d1b627e46306d93e |
refs/heads/master | <file_sep>/**
* Carousel
* https://flickity.metafizzy.co/
*/
import Flickity from 'flickity';
import 'flickity/css/flickity.css';
export default function carousel() {
const carousel = document.querySelector('[data-js="carousel"]');
// When Carousel exists
if (carousel) {
// Flickity - fade in for no FOUC, vanilla JS
// https://codepen.io/desandro/pen/JGoGpm
var carouselInit = function () {
carousel.classList.remove('is-hidden');
carousel.offsetHeight;
new Flickity( carousel, {
// options
cellAlign: 'left',
wrapAround: true
} );
};
carouselInit();
}
}
<file_sep>/*
* @title Templates
* @description A task to compile templates via Twig.js
*/
// Dependencies
import {src, dest} from 'gulp';
import plumber from 'gulp-plumber';
import twig from 'gulp-twig';
import errorHandler from '../util/errorHandler.js';
import beautify from 'gulp-jsbeautifier';
const gulpData = require('gulp-data')
const path = require('path')
const fs = require('fs')
// Config
import {paths} from "../config";
// Task
export function templates() {
return src(paths.templates.src)
.pipe(plumber({errorHandler}))
.pipe(gulpData(function (file) {
let filePath = paths.templates.data + path.basename(file.path) + '.json';
if(fs.existsSync(filePath)){
return JSON.parse(fs.readFileSync(filePath))
}
}))
.pipe(twig())
.pipe(beautify({
indent_size: 2
}))
.pipe(dest(paths.templates.dest))
};
<file_sep>/*
* @title App
* @description Application entry point
*/
// Polyfills
import 'Utils/_closest.polyfill.js';
import 'Utils/_matches.polyfill.js';
// Misc
// Use log() instead of console.log()
// const log = console.log.bind(console);
// Modules
import carousel from 'Modules/carousel/carousel';
import navbar from 'Modules/navbar/navbar';
import searchOverlay from 'Modules/search-overlay/search-overlay';
// Components
import collapse from 'Components/collapse.js';
import smoothScroll from 'Components/smooth-scroll';
import toggleElement from 'Components/toggle-element';
document.addEventListener('DOMContentLoaded', function() {
// Modules
carousel();
navbar();
searchOverlay();
// Components
collapse();
smoothScroll();
toggleElement();
})
<file_sep>/**
* Smooth Scroll
* https://github.com/tsuyoshiwada/sweet-scroll
*/
import SweetScroll from 'sweet-scroll';
export default function smoothScroll() {
const sweetScroll = new SweetScroll({ /* some options */ });
}
<file_sep>/**
* Navbar
*/
// import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
const throttleTime = 200;
export default function navbar() {
const navbar = document.querySelector('[data-js="navbar"]');
// When Navbar exists
if (navbar) {
// Show an overlay on the navbar toggler click
var trigger = function () {
document.addEventListener('click', function (e) {
if (e.target.closest('[data-js="navbar-toggler"]')) {
e.preventDefault();
document.body.classList.toggle('navbar--opened');
}
}, false);
};
trigger();
// Navbar becomes transparent when scrolling down.
var onScrollTransparent = function () {
const navbarPixels = 150;
if (navbar.classList.contains('navbar--fixed-transparent')) {
function navbarTransparent() {
let scrolled = document.scrollingElement.scrollTop;
let position = navbar.offsetTop;
if (scrolled > position + navbarPixels) {
navbar.classList.add('navbar--scrolled');
} else {
navbar.classList.remove('navbar--scrolled');
}
}
window.addEventListener('scroll', throttle(navbarTransparent, throttleTime));
}
};
onScrollTransparent();
// Navbar slides out of view when scrolling down and slides back
// in when scrolling up
// Based on
// https://dev.to/changoman/showhide-element-on-scroll-w-vanilla-js-3odm
var onScrollToggle = function () {
const navbarPixels = 150;
let scrollPos = 0;
if (navbar.classList.contains('navbar--fixed-toggle')) {
function navbarShowHide() {
var scrolled = document.scrollingElement.scrollTop;
var position = navbar.offsetTop;
if (scrolled > position + navbarPixels) {
let windowY = window.scrollY;
if (windowY < scrollPos) {
// Scrolling UP
navbar.classList.add('navbar-visible');
navbar.classList.remove('navbar-hidden');
} else {
// Scrolling DOWN
navbar.classList.add('navbar-hidden');
navbar.classList.remove('navbar-visible');
}
scrollPos = windowY;
}
}
window.addEventListener('scroll', throttle(navbarShowHide, throttleTime));
}
};
onScrollToggle();
}
}
| c6c03ebbb9d60aca1d7ca9cdbd218f7b451b01bb | [
"JavaScript"
] | 5 | JavaScript | SuperGodAsk/webpack-twig-boilerplate | 2b964fa89f5cc2d1ee920547e98b635e7ba64bd9 | ed6cf4e63e14c4818624652b42a7eda273c561d1 |
refs/heads/master | <file_sep>const express = require('express');
const app = express();
const port = 5000;
app.get('/',(req,res)=>{
res.send('<NAME>');
})
app.listen(port,()=>{
console.log('server name is running');
}) | d33b5aa5cdc792eeba1705186ade14eb3f310155 | [
"JavaScript"
] | 1 | JavaScript | muhammadahmed29/node-js-namefile | 9667655addf3773c518c3789167de1a4c8e13c21 | 7ba9a6560ecf8b2de02456efbef1b2d7f5742a14 |
refs/heads/master | <repo_name>OrionStark/Location-Status<file_sep>/LocationStatus/LocationStatus/WeatherStatus.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Newtonsoft.Json;
using LocationStatus.Model;
using LocationStatus.DataPack;
namespace LocationStatus
{
public partial class WeatherStatus : ContentPage
{
protected override bool OnBackButtonPressed()
{
App.Current.MainPage.Navigation.PopAsync(true);
return base.OnBackButtonPressed();
}
/// <summary>
/// XML Mode
/// </summary>
/// <param name="data">XML object value</param>
public WeatherStatus(Weather_XML_Data data)
{
InitializeComponent();
//this.DATA = data;
this.condition_lbl.Text = data.condition.First().ToString().ToUpper() +
data.condition.Substring(1);
this.temperature_lbl.Text += data.TEMP_IN_F + " F";
this.wind_d_lbl.Text += data.Wind_direction.First().ToString().ToUpper() +
data.Wind_direction.Substring(1);
this.wind_type.Text += data.wind_type.First().ToString().ToUpper() +
data.wind_type.Substring(1);
this.wind_speed.Text += data.windspeed;
this.city_name.Text = data.city.First().ToString().ToUpper() +
data.city.Substring(1);
}
/// <summary>
/// JDON Mode
/// </summary>
/// <param name="data">JSON object value</param>
public WeatherStatus(Weather_Data data)
{
InitializeComponent();
//this.JSON_Data = data;
this.condition_lbl.Text = data.weather[0].description.First().ToString().ToUpper()
+ data.weather[0].main.Substring(1);
this.wind_d_lbl.Text += data.wind.deg.ToString() + " Degrees";
this.wind_speed.Text += data.wind.speed.ToString();
this.temperature_lbl.Text += data.main.temp.ToString() + " F";
this.city_name.Text = "Your Location Status";
}
}
}
<file_sep>/LocationStatus/LocationStatus/MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform;
using Xamarin.Forms.PlatformConfiguration;
using Newtonsoft.Json;
using LocationStatus.Model;
namespace LocationStatus
{
public partial class MainPage : ContentPage
{
Weather weather = new Weather();
public MainPage()
{
InitializeComponent();
#if __ANDROID__
img_icon.Source = ImageSource.FromResource("LocationStatus.Droid.Resources.Drawable.cloudicon.png");
#elif __IOS__
img_icon.Source = ImageSource.FromResource("LocationStatus.iOS.Resources.cloudicon.png");
#else
img_icon.Source = ImageSource.FromResource("LocationStatus.UWP.cloudicon.png");
#endif
submit_btn.Clicked += (o, e) =>
{
try
{
#if SILVERLIGHT
weather.getCurrentWeather(City_Field.Text, Weather.MODE.JSON_MODE);
Navigation.PushAsync(new WeatherStatus(this.weather.weather));
#else
weather.getCurrentWeather(City_Field.Text, Weather.MODE.XML_MODE);
Navigation.PushAsync(new WeatherStatus(this.weather.weather_xml), true);
#endif
//condition.Text = weather.weather_xml.condition;
}
catch {
DisplayAlert("Something went Wrong", "Please check your internet connection/n" +
"or the API isn't ready yet", "OK");
}
};
}
protected override void OnDisappearing()
{
this.City_Field.Text = "";
}
}
}
<file_sep>/LocationStatus/LocationStatus/Model/Weather.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using LocationStatus.DataPack;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;
using Xamarin.Forms.Platform;
using Xamarin.Forms.PlatformConfiguration;
using System.Threading.Tasks;
namespace LocationStatus.Model
{
class Weather
{
public enum MODE {
JSON_MODE,
XML_MODE
}
private const string ORION_API_KEY = "99ff815581920ce4a745369635fae80f";
public Weather_Data weather { private set; get; }
public Weather_XML_Data weather_xml { private set; get; }
private HttpClient client;
public MODE Mode;
public Weather()
{
weather = new Weather_Data();
weather_xml = new Weather_XML_Data();
}
private async Task getAsObjectAsync(string location)
{
var json = await getWeatherConditionAsync(location);
Weather_Data data = JsonConvert.DeserializeObject<Weather_Data>(json);
this.weather = data;
}
private async Task<string> getWeatherConditionAsync( string Location )
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
Uri url = new Uri(string.Format("http://api.openweathermap.org/data/2.5/weather?q=" +
Location + "&APPID=" + ORION_API_KEY));
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return content;
}
else {
return response.ReasonPhrase;
}
}
private void getWithXML(string Location)
{
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument { XmlResolver = null };
xmlDocument.Load(string.Format("http://api.openweathermap.org/data/2.5/weather?q="
+ Location + "&mode=xml&units=imperial&APPID=" + ORION_API_KEY));
this.weather_xml.city = xmlDocument.SelectSingleNode("current/city").Attributes["name"].InnerText;
this.weather_xml.TEMP_IN_F = xmlDocument.SelectSingleNode("current/temperature").Attributes["value"].InnerText;
this.weather_xml.LOW = xmlDocument.SelectSingleNode("current/temperature").Attributes["min"].InnerText;
this.weather_xml.HIGH = xmlDocument.SelectSingleNode("current/temperature").Attributes["max"].InnerText;
this.weather_xml.windspeed = xmlDocument.SelectSingleNode("current/wind/speed").Attributes["value"].InnerText;
this.weather_xml.condition = xmlDocument.SelectSingleNode("current/weather").Attributes["value"].InnerText;
this.weather_xml.Wind_direction = xmlDocument.SelectSingleNode("current/wind/direction").Attributes["name"].InnerText;
this.weather_xml.wind_type = xmlDocument.SelectSingleNode("current/wind/speed").Attributes["name"].InnerText;
}
public void getCurrentWeather(string city, MODE mode)
{
switch (mode)
{
case MODE.JSON_MODE:
this.getAsObjectAsync(city).RunSynchronously();
break;
case MODE.XML_MODE:
this.getWithXML(city);
break;
default:
this.getWithXML(city);
break;
}
}
}
}
<file_sep>/LocationStatus/LocationStatus/DataPack/Weather_Data.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LocationStatus.DataPack
{
public class Weather_Data
{
public List<W_Description> weather { set; get; }
public Temperature main { set; get; }
public Wind wind { set; get; }
}
}
<file_sep>/README.md
# Location-Status
Hybrid mobile apps for check weather depends on your input city name (Tested in Android)
<file_sep>/LocationStatus/LocationStatus/DataPack/Weather_XML_Data.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LocationStatus.DataPack
{
public class Weather_XML_Data
{
public string city;
public string windspeed;
public string condition;
public string TEMP_IN_F;
public string Wind_direction;
public string HIGH;
public string LOW;
public string wind_type;
public Weather_XML_Data()
{
this.city = "No-Data";
this.windspeed = "No-Data";
this.condition = "No-Data";
this.Wind_direction = "No-Data";
this.TEMP_IN_F = "No-Data";
this.HIGH = "No-Data";
this.LOW = "No-Data";
this.wind_type = "No-Data";
}
}
}
<file_sep>/LocationStatus/LocationStatus/DataPack/W_Description.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LocationStatus.DataPack
{
public class W_Description
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
}
<file_sep>/LocationStatus/LocationStatus/DataPack/Wind.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LocationStatus.DataPack
{
public class Wind
{
public int speed { get; set; }
public int deg { get; set; }
}
}
| d5d6924d6793793294bcb792acde32f722613d12 | [
"Markdown",
"C#"
] | 8 | C# | OrionStark/Location-Status | f7ca53447814bf81c4a1d9d779e6b89bcf693856 | 8d2a68ddfdc5e9614d1c05284654b67b1425ad81 |
refs/heads/master | <file_sep>package main
import "errors"
// Version of the item.
type Version struct {
Version string `json:"ver,omitempty"`
StemCell string `json:"sc,omitempty"`
}
// Status of this platform.
type Status struct {
Error string `json:"error,omitempty"`
Versions map[string]Version `json:"versions,omitempty"`
}
const (
legacyVersionString = "\u2264 1.6"
// UnknownVersionString holds the unknown version string.
UnknownVersionString = "unknown"
// These are the labels for opsman and ERT. They have the special
// characters to ensure they are sorted first.
nameOpsMan = "\001Ops Man"
nameErt = "\002ERT"
)
// StandardNames are the mappings between labels and nice names.
// NOTE: Add tile translations here: if the value is empty, then that
// entry will be ignored.
var StandardNames = map[string]string{
"cf": nameErt,
"p-bosh": "",
"p-mysql": "MySql Tile",
}
// NewStatus will create a new status object.
func NewStatus(includes *Includes) (status *Status, err error) {
var opsManClient *OpsManClient
if opsManClient, err = NewOpsManClient(); err == nil {
info := DiagnosticReport{}
if err = opsManClient.GetInfo(&info); err == nil {
if !info.Legacy {
status = &Status{
Versions: map[string]Version{
nameOpsMan: Version{
Version: info.Versions.Release,
},
},
}
for _, item := range info.Products.Deployed {
stemcell := ""
if includes.StemCellVersion {
stemcell = item.Stemcell
}
if name, ok := StandardNames[item.Name]; ok {
// Ignore empty values.
if len(name) > 0 {
status.Versions[name] = Version{
Version: item.Version,
StemCell: stemcell,
}
}
} else {
status.Versions[item.Name] = Version{
Version: item.Version,
StemCell: stemcell,
}
}
}
} else {
status = &Status{
Versions: map[string]Version{
nameOpsMan: {Version: legacyVersionString},
nameErt: {Version: legacyVersionString},
},
}
}
}
}
if err != nil {
status = &Status{
Error: err.Error(),
}
} else {
if status == nil {
err = errors.New("Unknown status")
} else if len(status.Versions) == 0 {
err = errors.New("No versions found")
}
}
return
}
<file_sep># pcf-status
This application will return useful information about a PCF install.
## Installing
Simply push the application to you cloud foundry.
```Bash
> cf push -f manifest.yml
```
for some of the older foundations, you may need to specify the go buildpack:
```Bash
> cf push -f manifest.yml -b https://github.com/cloudfoundry/go-buildpack.git
```
## Configuration
Apply the following configuration to the application instance.
| Environment Variable | Details |
|:--------------------:|:--------|
| `UAA_ADDRESS` | This is the URL to the UAA and Ops Manager instance. Example: `https://192.168.0.0` |
| `OPSMAN_USER` | This is the Ops Man user that you want to use. |
| `OPSMAN_PASSWORD` | <PASSWORD> is the password to the Ops Man user. |
## Raw Data
Note that for sorting reasons, we inject the `\u0001` and `\u0002`. This may not be a great
implementation, but it helped keep the Ops Man and ERT in the order we wanted.
You can query the application using the following route: `http://<Application Route>/versions`
It will then return:
```JSON
{
"versions":{
"\u0001Ops Man":{
"ver":"1.7.13.0"
},
"\u0002ERT":{
"ver":"1.7.21-build.2"
},
"MySql Tile":{
"ver":"1.7.13"
}
}
}
```
To include the stemcell versions add a query parameter named `scv` and set it to `true`.
For example `http://<Application Route>/versions?scv=true` would return:
```JSON
{
"versions":{
"\u0001Ops Man":{
"ver":"1.7.13.0"
},
"\u0002ERT":{
"ver":"1.7.21-build.2",
"sc":"3232.19"
},
"MySql Tile":{
"ver":"1.7.13",
"sc":"3232.19"
}
}
}
```
## Badges
Badges have been removed and another project controls them now: https://github.com/ECSTeam/status-badge
<file_sep>/*main is the entry point package for this application.
*
*/
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/rs/cors"
)
// port and portFlag handle the port for this application. The default is
// arbitrarily set to 8080.
var port int
var host string
var (
portFlag = flag.Int("port", 8080, "The port to use.")
hostFlag = flag.String("host", "", "The host name.")
)
// init the program.
func init() {
var err error
log.Print("Initializing the application")
flag.Parse()
portStr := os.Getenv("PORT")
if port, err = strconv.Atoi(portStr); err != nil {
port = *portFlag
err = nil
}
host = os.Getenv("HOST")
if len(strings.TrimSpace(host)) <= 0 {
host = *hostFlag
}
}
// reportError will report an error result.
func reportError(err error, format string, resp http.ResponseWriter, status int) {
log.Printf("Unable to get status: %s", err.Error())
resp.WriteHeader(status)
resp.Write([]byte(err.Error()))
}
// handlePanic will capture any panics and return a message to the output.
func handlePanic(resp http.ResponseWriter, status int) {
if p := recover(); p != nil {
messageFmt := "Unhandled panic: %s"
var err error
switch p.(type) {
case nil:
// normal case, just ignore.
case string:
messageFmt = p.(string)
err = errors.New(messageFmt)
case error:
err = p.(error)
default:
err = errors.New(fmt.Sprint(p))
}
if err != nil {
reportError(err, messageFmt, resp, status)
}
}
}
// httpHandler handles the http requests.
func httpHandler(resp http.ResponseWriter, req *http.Request) {
defer handlePanic(resp, http.StatusInternalServerError)
var err error
switch req.URL.Path {
case "/versions":
{
switch req.Method {
case "GET":
{
includes := NewIncludes(req.URL.Query())
var status *Status
if status, err = NewStatus(includes); err == nil {
var bytes []byte
if bytes, err = json.Marshal(status); err == nil {
// First, add the headers as the Write will start streaming right away.
resp.Header().Set("Content-Type", "application/json")
resp.Header().Set("Cache-Control", "no-cache")
// TODO: we may need to remove the \u0001 and \u0002 from the
// result because this was a hack to sort the labels
// correctly. The SVG though doesn't mind.
_, err = resp.Write(bytes)
}
}
}
}
}
default:
err = errors.New("Unknown route.")
}
if err != nil {
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte(err.Error()))
}
}
// main entry point.
func main() {
log.Print("Starting application")
c := cors.New(cors.Options{
AllowedMethods: []string{"GET"},
})
handler := http.HandlerFunc(httpHandler)
endpoint := fmt.Sprintf("%s:%d", host, port)
if err := http.ListenAndServe(endpoint, c.Handler(handler)); err != nil {
log.Fatalf("Failed to listen on endpoint '%s': %s", endpoint, err.Error())
} else {
log.Printf("Started application on endpoint: '%s'", endpoint)
}
}
<file_sep>package main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
/*
reportUrls := {
"/api/v0/diagnostic_report",
"/api/v0/diagnostic_report.json",
}
*/
// OpsManClient is the client for the ops manager.
type OpsManClient struct {
address string
token string
}
// DiagnosticReport is the result from /api/v0/diagnostic_report
type DiagnosticReport struct {
Legacy bool `json:"-"`
Versions struct {
Schema string `json:"installation_schema_version"`
Meta string `json:"metadata_version"`
Release string `json:"release_version"`
} `json:"versions"`
Products struct {
Deployed []struct {
Name string `json:"name"`
Version string `json:"version"`
Stemcell string `json:"stemcell"`
} `json:"deployed"`
} `json:"added_products"`
Stemcells []string `json:"stemcells"`
}
// OAuthPayload is the wrapper for the oauth token.
type OAuthPayload struct {
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
}
// HeaderValue is the authorization header value.
func (payload OAuthPayload) HeaderValue() (output string) {
output = fmt.Sprintf("%s %s", payload.TokenType, payload.AccessToken)
return
}
// NewOpsManClient will create a new ops manager client.
func NewOpsManClient() (opsManClient *OpsManClient, err error) {
user := os.Getenv("OPSMAN_USER")
address := os.Getenv("UAA_ADDRESS")
password := os.Getenv("OPSMAN_<PASSWORD>")
if len(user) == 0 || len(address) == 0 || len(password) == 0 {
err = errors.New("Misconfigured")
return
}
log.Printf("Logging in as: %s", user)
opsManClient = &OpsManClient{
address: address,
}
path := fmt.Sprintf("/uaa/oauth/token?grant_type=password&username=%s&password=%s", user, password)
err = opsManClient.callURL(path, func(code int, data []byte) (e error) {
var token OAuthPayload
if codeIsGood(code) {
if e = json.Unmarshal(data, &token); e == nil {
opsManClient.token = token.HeaderValue()
}
}
return
})
return
}
func codeIsGood(code int) bool {
return code >= http.StatusOK && code < http.StatusBadRequest
}
// GetInfo will return the info.
func (opsManClient *OpsManClient) GetInfo(report *DiagnosticReport) (err error) {
err = opsManClient.callURL("/api/v0/diagnostic_report.json", func(code int, data []byte) (e error) {
if codeIsGood(code) {
if e = json.Unmarshal(data, report); e == nil {
// cleanup the stemcell versions here.
for index, prod := range report.Products.Deployed {
// This is assuming that the format will not change...
// currently it is: bosh-stemcell-3232.19-vsphere-esxi-ubuntu-trusty-go_agent.tgz
if parts := strings.Split(prod.Stemcell, "-"); len(parts) >= 3 {
report.Products.Deployed[index].Stemcell = parts[2]
}
}
}
} else if code == http.StatusNotFound {
report.Legacy = true
}
return
})
return
}
// callUrl will call the url and add the appropriate headers.
func (opsManClient *OpsManClient) callURL(path string, operation func(int, []byte) error) (err error) {
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
url := opsManClient.address + path
var req *http.Request
if req, err = http.NewRequest("GET", url, nil); err == nil {
if len(opsManClient.token) != 0 {
req.Header.Add("Authorization", opsManClient.token)
} else {
// shortcut for opsman login.
req.SetBasicAuth("opsman", "")
}
var resp *http.Response
if resp, err = client.Do(req); err == nil {
defer resp.Body.Close()
var resBody []byte
code := resp.StatusCode
if codeIsGood(code) {
if resBody, err = ioutil.ReadAll(resp.Body); err == nil {
}
}
err = operation(code, resBody)
}
}
return
}
<file_sep>package main
import (
"net/url"
"reflect"
"strconv"
)
// Includes in the payloads.
type Includes struct {
// StemCellVersion flag.
StemCellVersion bool `qs:"scv"`
}
// NewIncludes will create a new includes object.
func NewIncludes(queryString url.Values) (includes *Includes) {
includes = &Includes{}
if len(queryString) > 0 {
t := reflect.TypeOf(*includes)
elem := reflect.ValueOf(includes).Elem()
for i := 0; i < t.NumField(); i++ {
structField := t.Field(i)
field := elem.Field(i)
if field.CanSet() {
qsName := structField.Tag.Get("qs")
strVal := queryString.Get(qsName)
if val, err := strconv.ParseBool(strVal); err == nil {
field.SetBool(val)
}
}
}
}
return
}
| ea9678b87fcb01073a56e750ff0b3467710bf909 | [
"Markdown",
"Go"
] | 5 | Go | jtgammon/pcf-status | 636164a7d18e386a3f038514488817e7cae72d58 | 083e05babe0e1954f5671b4953e5ab9618a8463f |
refs/heads/master | <file_sep>#include "../../include/people/pig.h"
#include "../../include/color.h"
namespace people {
Pig::Pig():
People(new color::Red, 'P', 0, 100, 3, 5) {
}
Pig::~Pig() {
}
void Pig::_todo() {
srand(time(0));
int randx = -1 + rand()%3, randy = -1 + rand()%3;
pos::Pos ps = get_pos();
move(pos::Pos(ps._x + randx, ps._y + randy));
}
int Pig::_meet(People *p) {
// 不打架
p -> injured(get_fight(), this);
return 0;
}
};
<file_sep>#include <pwd.h>
#include <unistd.h>
#include <string>
namespace who {
extern std::string user_home(uid_t uid)
{
if(uid == 0x66ccf) uid = geteuid();
struct passwd *pass = getpwuid(uid);
return std::string(pass->pw_dir);
}
extern std::string user_shell(uid_t uid)
{
if(uid == 0x66ccf) uid = geteuid();
struct passwd *pass = getpwuid(uid);
return std::string(pass->pw_shell);
}
extern std::string user_name(uid_t uid)
{
if(uid == 0x66ccf) uid = geteuid();
struct passwd *pass = getpwuid(uid);
return std::string(pass->pw_name);
}
};
<file_sep>OBJECT=build/color.o build/cursor.o build/ytime.o build/pos.o build/who.o \
build/file_processor.o
COMPILER=g++
CXXFLAGS=-Wall -Werror -Wshadow -O2 -DNDEBUG -I ../include/
TESTCASE=test/input test/ytime test/who test/file_processor
all: build-dir ${OBJECT}
test: build-dir ${OBJECT} test-dir ${TESTCASE}
build-dir:
mkdir -p build
build/color.o: color.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/cursor.o: cursor.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/ytime.o: ytime.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/pos.o: pos.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/input.o: input.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/who.o: who.cpp
${COMPILER} ${CXXFLAGS} -c $^ -o $@
build/file_processor.o: file_processor.c
${COMPILER} ${CXXFLAGS} -c $^ -o $@
test-dir:
mkdir -p test
test/input: build/ytime.o build/input.o test-input.cpp
${COMPILER} ${CXXFLAGS} $^ -o $@
test/ytime: build/input.o build/ytime.o test-ytime.cpp
${COMPILER} ${CXXFLAGS} $^ -o $@
test/who: build/who.o test-who.cpp
${COMPILER} ${CXXFLAGS} $^ -o $@
test/file_processor: build/file_processor.o test-file_processor.c
${COMPILER} ${CXXFLAGS} $^ -o $@
clean:
rm -rf test build
<file_sep>#include <stdio.h>
#include "file_processor.h"
extern int process_file(void *processor)
{
struct file_processor *pthis = (struct file_processor*)processor;
FILE *fp = fopen(pthis->file_name, pthis->open_mode);
int ret;
if (fp == NULL)
return 1;
ret = pthis->process(fp, pthis);
fclose(fp);
return ret;
}
<file_sep>#include "../include/begin_flash.h"
#include "../include/all_people.h"
#include "../include/all_map.h"
#include "../include/users.h"
#include "../include/input.h"
#include "../include/cursor.h"
#include "../include/othertodo.h"
int main(int, const char **) {
cursor::hide();
begin_flash::welcome();
people::Player *self = new people::Player();
if(users::login(self))
return 1;
map::Map *city = new map::Maincity();
self->join_map(city);
othertodo::Queue que;
que.add_people(self);
while(self->get_map()) {
que.todo();
}
cursor::display();
remove("py_output");
delete city;
}
<file_sep>#include "../include/othertodo.h"
#include "../include/all_people.h"
namespace othertodo {
std::vector<std::pair<people::People *, int> > Queue::_vector;
Queue::Queue() {
}
Queue::~Queue() {
for(auto p : _self_vector)
delete p;
}
void Queue::add_people(people::People* p) {
_vector.push_back(std::make_pair(p, 0));
_self_vector.push_back(p);
}
void Queue::todo() {
for(auto it=_vector.begin(); it!=_vector.end(); )
if(not it -> first -> get_map()) {
// 清除死亡者
it = _vector.erase(it);
} else
it ++;
for(auto &pr : _vector) {
if(not pr.second) {
pr.first->todo();
pr.second = pr.first -> speed;
}
else {
pr.second --;
}
}
}
};
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include "file_processor.h"
struct write_data_to_file {
struct file_processor base;
const char *msg;
};
int write_data(FILE *fp, struct file_processor *pthis)
{
fputs(((struct write_data_to_file*)pthis)->msg, fp);
return 0;
}
#define new_write_data_to_file(file, msg) {\
{ \
file, "w", \
write_data \
}, \
msg \
}
int main(void)
{
FILE *tmp;
const char *msg = "hello, world";
const char *tmpfile = "/tmp/tmp-file-luotianyi-is-the-best.txt";
char rbuf[256];
/*
用模板方式来写入文件
*/
struct write_data_to_file wd = new_write_data_to_file(tmpfile, msg);
if (process_file(&wd)) {
fprintf(stderr, "%s\n", strerror(errno));
return EXIT_FAILURE;
}
/*
然后再用传统方式来看一看效果.
*/
tmp = fopen(tmpfile, "r");
if (tmp == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
} else {
rbuf[0] = '\0';
if (fgets(rbuf, sizeof(rbuf), tmp) == NULL)
fprintf(stderr, "%s\n", strerror(errno));
else
assert(strcmp(rbuf, msg) == 0);
fclose(tmp);
}
printf("write:%s\nread :%s\n", msg, rbuf);
remove(tmpfile);
return 0;
}
<file_sep>#ifndef FILE_PROCESSOR_H_
#define FILE_PROCESSOR_H_
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdio.h>
struct file_processor {
const char *file_name, *open_mode;
int (*process)(FILE* fp, struct file_processor *pthis);
};
/*
W A R N I N G
processor的第一个元素必须为file_processor.
这里本该是``int process_file(file_processor *pthis)''
写成void可以在调用时更加方便.
*/
int process_file(void *processor);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* FILE_PROCESSOR_H_ */
<file_sep>#include <iostream>
#include <string>
#include "who.h"
int main(void)
{
std::cout << "User: " << who::user_name() << std::endl;
std::cout << "Home: " << who::user_home() << std::endl;
std::cout << "Shell: " << who::user_shell() << std::endl;
std::cout << std::endl;
std::cout << "User: " << who::user_name(0) << std::endl;
std::cout << "Home: " << who::user_home(0) << std::endl;
std::cout << "Shell: " << who::user_shell(0) << std::endl;
return 0;
}
<file_sep>#include <iostream>
#include <cstring>
#include <functional>
#include "../include/ytime.h"
#include "../include/color.h"
#include "../include/cursor.h"
#include "../include/input.h"
#include "../include/begin_flash.h"
#include "../include/ascii_flash.h"
namespace begin_flash {
Marix::Marix(pos::Coord_map<char> _map, color::Color *color):
_map(_map), color(color) {
}
Marix::~Marix() {
delete color;
}
void Marix::ob_print() {
color::White wh;
for(int t=0; t<_map.high+_map.width; t++) {
for(int i=0; i<_map.high; i++) {
for(int j=0; j<_map.width; j++)
if(i + j == t) {
wh.change_fore();
std::cout << _map(i, j);
} else if(i + j < t) {
color->change_fore();
std::cout << _map(i, j);
}
std::cout << std::endl;
}
ytime::ysleep(100);
cursor::up(_map.high);
}
cursor::down(_map.high);
color->reset_fore();
input::clear();
}
void Marix::mid_disapeear() {
cursor::up(_map.high);
color::White wl;
int rx = _map.high >> 1, ry = _map.width >> 1; // 矩阵中心坐标
for(int t=0; t*2<_map.high+_map.width; t ++) {
for(int i=0; i<_map.high; i++) {
for(int j=0; j<_map.width; j++)
if(std::abs(i - rx) + std::abs(j - ry) < t)
std::cout << ' ';
else if(std::abs(i - rx) + std::abs(j - ry) == t) {
wl.change_fore();
std::cout << _map(i, j);
} else {
color->change_fore();
std::cout << _map(i, j);
}
std::cout << std::endl;
}
ytime::ysleep(100);
cursor::up(_map.high);
}
color->reset_fore();
input::clear();
}
void flash(std::string info, bool speedup) {
// 以黑白加速闪动特效输出 [info]
color::Color *cr[2] = {new color::Black(0), new color::White(0)};
for(int i=0; i < (speedup?20:10); i++) {
cr[i & 1]->change_fore();
cursor::to_head();
std::cout << info << std::endl;
cursor::up();
if(speedup)
ytime::ysleep(200 - 10 * i);
else
ytime::ysleep(200);
}
input::clear();
cr[0]->reset_fore();
delete cr[0];
delete cr[1];
}
void welcome() {
// 欢迎界面
cursor::clear_screen();
cursor::set_to(0, 0);
begin_flash::flash("Welcome to yzzl", true);
const int flash_sl = 6;
std::function<pos::Coord_map<char>()> flash[flash_sl]
= {Flash1, Flash2, Flash3, Flash4, Flash5, Flash6 };
srand(time(0));
color::Color *color = nullptr;
int rd = rand() % 100;
if(rd < 60) color = new color::Green();
else if(rd < 90) color = new color::Red();
else color = new color::Random();
begin_flash::Marix mar(flash[rand()%flash_sl](), color);
mar.ob_print();
mar.mid_disapeear();
}
void thanks() {
// 鸣谢
cursor::clear_screen();
cursor::set_to(0, 0);
begin_flash::flash("Yzzl 的诞生还要感谢许多人和软件、网站", false);
cursor::down();
const int high = 11, width = 80;
const char s[high][width] = {
" ",
"<NAME>: His '<NAME>' inspire me to create yzzl ",
" whose idea is from that. ",
" ",
"Ld_liaomo: help me to write lib files which needed. ",
" ",
"https://www.bootschool.net/ascii: Provide the source of the ",
" opening animation which is made by ascii painting. ",
" ",
"And thank you to play this! ",
" ",
};
pos::Coord_map<char> cmap(high, width);
for(int i=0;i<high;i++)
for(int j=0;j<width;j++)
cmap(i, j) = s[i][j] ? s[i][j] : ' ';
begin_flash::Marix mar(cmap, new color::Green);
mar.ob_print();
mar.mid_disapeear();
}
void progress_bar(double x, int size) {
cursor::right(size);
putchar('|');
cursor::left(size + 1);
size *= 8;
int need;
for(need=size*x; need>=8; need -= 8)
printf("█"); // 完整方块
switch(need) {
case 1: printf("▏"); break; // 八分之一
case 2: printf("▎"); break; // 八分之二
case 3: printf("▍"); break; // 八分之三
case 4: printf("▌"); break; // 八分之四
case 5: printf("▋"); break; // 八分之五
case 6: printf("▊"); break; // 八分之六
case 7: printf("▉"); break; // 八分之七
}
puts("");
}
void box(pos::Pos p, int high, int width, int type, color::Color *cr) {
/* 边框 1
╔════╗
║ ║
╚════╝
*/
/* 边框 2
┌────┐
│ │
└────┘
*/
cr->change_fore();
const std::string s1 = "┌", s2 = "│", s3 = "└", s4 = "─", s5 = "┘", s6 = "┐";
cursor::set_to(p._x, p._y);
std::cout << s1;
for(int i=1; i<=high; i++) {
cursor::set_to(p._x + i, p._y);
std::cout << s2;
cursor::set_to(p._x + i, p._y + width + 1);
std::cout << s2;
}
cursor::set_to(p._x + high + 1, p._y);
std::cout << s3;
for(int j=1; j<=width; j++) {
cursor::set_to(p._x, p._y + j);
std::cout << s4;
cursor::set_to(p._x + high + 1, p._y + j);
std::cout << s4;
}
cursor::set_to(p._x + high + 1, p._y + width + 1);
std::cout << s5;
cursor::set_to(p._x, p._y + width + 1);
std::cout << s6;
cr->reset_fore();
}
};
<file_sep>#ifndef pig_H
#define pig_H
#include "people.h"
namespace people {
class Pig: public People {
protected:
void _todo();
int _meet(People *);
public:
Pig();
~Pig();
};
};
#endif
<file_sep>#include "../../include/people/player.h"
#include "../../include/cursor.h"
#include "../../include/color.h"
#include "../../include/all_map.h"
#include "../../include/all_floor.h"
#include "../../include/input.h"
#include "../../include/begin_flash.h"
namespace people {
Player::Player():
People(new color::Blue, '@', 3, 1000, 10, 0) {
}
Player::~Player() {
}
char Player::_get_face() {
switch(_fg) {
case 'h': return '<';
case 'j': return 'v';
case 'k': return '^';
case 'l': return '>';
default: return face;
}
}
int Player::login(std::string name, std::string pass) {
// 在接口调好之前,先用着吧, ~~不碍事~~
int res =
system(("python3 python/user_login.py " + name + " " + pass + " l").c_str());
if(res == 0) {
FILE *read =fopen("py_output", "r");
fscanf(read, "exp: %lld\n", &m_exp);
}
return res;
}
int Player::regis(std::string name, std::string pass) {
// 在接口调好之前,先用着吧, ~~不碍事~~
int res =
system(("python3 python/user_login.py " + name + " " + pass + " r").c_str());
if(res == 0) {
FILE *read =fopen("py_output", "r");
fscanf(read, "exp: %lld\n", &m_exp);
}
return res;
}
void Player::_print_map(int high, int width) {
cursor::clear_screen();
cursor::set_to(0, 0);
for(int i=-high; i<=high; i++) {
for(int j=-width; j<=width; j++) {
if(not i and not j) { // Player 本身
color->change_fore();
putchar(_get_face());
}
else {
People *p = get_map()->get_people(get_pos(), i, j);
if(p) { // 该位置有人
p->color->change_fore();
putchar(p->face);
} else {
floor::Floor *f = get_map()->get_floor(get_pos(), i, j);
if(f) {
f->color->change_fore();
putchar(f->face);
} else {
color->reset_fore();
putchar(' ');
}
}
}
}
std::cout << std::endl;
}
color->reset_fore();
}
void Player::_print_info(int high, int width) {
cursor::set_to(1, width + 1);
printf("当前位置:%s (%d, %d)\n",
get_map()->name.c_str(), get_pos()._x, get_pos()._y);
cursor::set_to(2, width + 1);
printf("Your HP: ");
begin_flash::progress_bar(double(m_hp) / get_hpmax(), 20);
cursor::set_to(high, 0);
// To do something
}
void Player::_analyze_choose(char cs) {
pos::Pos ps = get_pos();
switch(cs) {
case 'h': _fg = 'h'; move(pos::Pos(ps._x, ps._y - 1)); break;
case 'j': _fg = 'j'; move(pos::Pos(ps._x + 1, ps._y)); break;
case 'k': _fg = 'k'; move(pos::Pos(ps._x - 1, ps._y)); break;
case 'l': _fg = 'l'; move(pos::Pos(ps._x, ps._y + 1)); break;
default: _fg = ' '; break;
}
}
void Player::_todo() {
const int high = 6, width = 6; // 视野半径
_print_map(high, width);
color::Color *cr = new color::Random();
begin_flash::box(pos::Pos(0, width * 2 + 1), 5, 40, 0, cr);
_print_info(high << 1 | 1, width << 1 | 1);
int choose = input::ifgetch(0.1);
if(~ choose)
_analyze_choose(choose);
else
_fg = ' ';
delete cr;
}
int Player::_meet(People *p) {
p->injured(get_fight(), this);
return 0;
}
};
<file_sep>COMPILER=g++
CXXFLAGS=-Wall -Werror -I ./include/ -std=c++11
OBJECT=build/begin_flash.o build/color.o build/cursor.o build/pos.o \
build/ytime.o build/input.o build/people.o build/player.o build/map.o \
build/floor.o build/base_floor.o build/users.o build/maincity.o \
build/ascii_flash.o build/pig.o build/othertodo.o
dist/yzzl: build dist ${OBJECT} build/main/yzzl.o build/pylock
${COMPILER} ${OBJECT} build/main/yzzl.o -o $@ -lpthread -std=c++11 # -I/usr/include/python3.6m -lpython3.6m
build/pylock:
sudo apt install python3 python3-pip
pip3 install leancloud
touch build/pylock
dist:
mkdir -p dist
build:
mkdir -p build
build/main/yzzl.o: main/yzzl.cpp include/*
mkdir -p build/main
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/begin_flash.o: source/begin_flash.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/color.o: lib/color.cpp
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/cursor.o: lib/cursor.cpp
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/pos.o: lib/pos.cpp
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/ytime.o: lib/ytime.cpp
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/people.o: source/people/people.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/player.o: source/people/player.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/map.o: source/map/map.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/floor.o: source/floor/floor.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/base_floor.o: source/floor/base_floor.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/input.o: lib/input.cpp
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/users.o: source/users.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/maincity.o: source/map/maincity.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/ascii_flash.o: source/ascii_flash.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/pig.o: source/people/pig.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
build/othertodo.o: source/othertodo.cpp include/*
${COMPILER} ${CXXFLAGS} -c $< -o $@
clean:
rm -rf build/* dist/*
# cd lib ; make clean ; cd ..
dist/yfl: build dist ${OBJECT} build/main/yfl.o
${COMPILER} ${OBJECT} build/main/yfl.o -o $@ -lpthread -std=c++11
build/main/yfl.o: main/yfl.cpp
mkdir -p build/main
${COMPILER} ${CXXFLAGS} -c $< -o $@
/usr/bin/yzzl: dist/yzzl
echo '#!/bin/bash' > $<_sys
echo cd `pwd` '&&' ./$< >> $<_sys
chmod +x $<_sys
sudo mv $<_sys $@
/usr/bin/yfl: dist/yfl
echo '#!/bin/bash' > $<_sys
echo cd `pwd` '&&' ./$< >> $<_sys
chmod +x $<_sys
sudo mv $<_sys $@
all: /usr/bin/yfl /usr/bin/yzzl
@echo
@echo installed!
<file_sep>#include <cstdio>
#include "../include/cursor.h"
/*
* Warning:
* fflush(stdout) is necessary because the control sequence may
* be buffered in memory without flush.
*/
namespace cursor {
void up(int times) {
printf("\033[%dA", times);
fflush(stdout);
}
void down(int times) {
printf("\033[%dB", times);
fflush(stdout);
}
void left(int times) {
printf("\033[%dD", times);
fflush(stdout);
}
void right(int times) {
printf("\033[%dC", times);
fflush(stdout);
}
void to_head() {
putchar('\r');
fflush(stdout);
}
void clear_screen() {
printf("\033[2J");
fflush(stdout);
}
void set_to(int x, int y) {
// 以 (0, 0) 为原点
printf("\033[%d;%dH", x + 1, y + 1);
fflush(stdout);
}
void back(int times) {
// 回退(删除) [times] 个字符
while(times --)
putchar('\b');
fflush(stdout);
}
void hide() {
// 隐藏光标
printf("\033[?25l");
fflush(stdout);
}
void display() {
// 显示光标
printf("\033[?25h");
fflush(stdout);
}
};
<file_sep>#ifndef map_H
#define map_H
#include "../pos.h"
#include "../othertodo.h"
namespace people {
class People;
};
namespace floor {
class Floor;
};
namespace map {
class Map {
protected:
pos::Coord_map<floor::Floor*> _floor;
pos::Coord_map<people::People*> _people;
othertodo::Queue _que;
public:
int high, width;
std::string name;
int people_move(people::People*, pos::Pos, pos::Pos);
virtual pos::Pos recieve(people::People *) = 0;
floor::Floor *get_floor(pos::Pos, int, int);
people::People *get_people(pos::Pos, int, int);
void after_leave(people::People *);
Map(int, int, std::string);
virtual ~Map();
};
};
#endif
<file_sep>#ifndef WHO_H_
#define WHO_H_
#include <unistd.h>
#include <string>
namespace who {
std::string user_home(uid_t uid = 0x66ccf);
std::string user_shell(uid_t uid = 0x66ccf);
std::string user_name(uid_t uid = 0x66ccf);
};
#endif /* WHO_H_ */
<file_sep>#include "../../include/people/people.h"
#include "../../include/floor/floor.h"
#include "../../include/map/map.h"
#include "../../include/color.h"
#include "../../include/ytime.h"
namespace people {
People::People(color::Color *color, char face, int clever,
long long _hpmax, long long _fight, int speed):
_lv(0), _hpmax(_hpmax), _fight(_fight),
color(color), face(face), m_exp(0), m_hp(_hpmax),
clever(clever), speed(speed) {
}
People::~People() {
delete color;
}
int People::goin(floor::Floor *f) {
f->meet(this);
// 之后在这提供派生类的接口
return 0;
}
int People::move(pos::Pos ne) {
// 在 _now_map 中移动
int moveres = get_map()->people_move(this, _pos.front(), ne);
if(moveres == 0) {
_pos.pop();
_pos.push(ne);
}
return moveres;
}
void People::todo() {
_todo();
}
void People::join_map(map::Map *m) {
_map.push(m);
pos::Pos ne = m->recieve(this);
_pos.push(ne);
}
void People::leave_map() {
get_map() -> after_leave(this);
_map.pop();
_pos.pop();
}
pos::Pos People::get_pos() {
if(_pos.empty())
return pos::Pos(0, 0);
return _pos.front();
}
map::Map *People::get_map() {
if(_map.empty())
return nullptr;
return _map.front();
}
long long People::get_hpmax() {
return _hpmax;
}
long long People::get_fight() {
return _fight;
}
int People::meet(People *p) {
int res = _meet(p);
return res;
}
void People::injured(long long fight, People *from) {
m_hp -= fight;
if(m_hp < 0) {
m_hp = 0;
leave_map();
}
}
};
<file_sep>#ifndef othertodo_H
#define othertodo_H
#include <vector>
#include <utility>
namespace people {
class People;
};
namespace othertodo {
class Queue {
protected:
static std::vector<std::pair<people::People *, int> > _vector;
std::vector<people::People *> _self_vector;
public:
void add_people(people::People*);
void todo();
Queue();
~Queue();
};
};
#endif
| d90f6023b2ce403a1b51acdcf8f6b8fd85285e26 | [
"C",
"Makefile",
"C++"
] | 18 | C++ | HNFMS-g2018/yzzl | 7396359d99d879f51c2b4c968c3f531f7d1d7d31 | 6d9716450be87e941739f4a2313738ef48f4b212 |
refs/heads/master | <file_sep>from flask import Flask
# creating an object
app=Flask(__name__)
# creating a route
@app.route('/')
def main():
return 'hello'
if __name__ == '__main__':
app.run(debug=True)
<file_sep># Get-started-with-Flask
User’s Guide
This part of the documentation, which is mostly prose, begins with some background information about Flask, then focuses on step-by-step instructions for web development with Flask.
Foreword
What does “micro” mean?
Configuration and Conventions
Growing with Flask
Foreword for Experienced Programmers
Thread-Locals in Flask
Develop for the Web with Caution
Installation
Python Version
Dependencies
Virtual environments
Install Flask
Install virtualenv
Quickstart
A Minimal Application
What to do if the Server does not Start
Debug Mode
Routing
Static Files
Rendering Templates
Accessing Request Data
Redirects and Errors
About Responses
Sessions
Message Flashing
Logging
Hooking in WSGI Middleware
Using Flask Extensions
Deploying to a Web Server
Tutorial
Project Layout
Application Setup
Define and Access the Database
Blueprints and Views
Templates
Static Files
Blog Blueprint
Make the Project Installable
Test Coverage
Deploy to Production
Keep Developing!
Templates
Jinja Setup
Standard Context
Standard Filters
Controlling Autoescaping
Registering Filters
Context Processors
Testing Flask Applications
The Application
The Testing Skeleton
The First Test
Logging In and Out
Test Adding Messages
Other Testing Tricks
Faking Resources and Context
Keeping the Context Around
Accessing and Modifying Sessions
Testing JSON APIs
Testing CLI Commands
Application Errors
Error Logging Tools
Error handlers
Logging
Debugging Application Errors
When in Doubt, Run Manually
Working with Debuggers
Logging
Basic Configuration
Email Errors to Admins
Injecting Request Information
Other Libraries
Configuration Handling
Configuration Basics
Environment and Debug Features
Builtin Configuration Values
Configuring from Files
Configuring from Environment Variables
Configuration Best Practices
Development / Production
Instance Folders
Signals
Subscribing to Signals
Creating Signals
Sending Signals
Signals and Flask’s Request Context
Decorator Based Signal Subscriptions
Core Signals
Pluggable Views
Basic Principle
Method Hints
Method Based Dispatching
Decorating Views
Method Views for APIs
The Application Context
Purpose of the Context
Lifetime of the Context
Manually Push a Context
Storing Data
Events and Signals
The Request Context
Purpose of the Context
Lifetime of the Context
Manually Push a Context
How the Context Works
Callbacks and Errors
Context Preservation on Error
Notes On Proxies
Modular Applications with Blueprints
Why Blueprints?
The Concept of Blueprints
My First Blueprint
Registering Blueprints
Blueprint Resources
Building URLs
Error Handlers
Extensions
Finding Extensions
Using Extensions
Building Extensions
Command Line Interface
Application Discovery
Run the Development Server
Open a Shell
Environments
Debug Mode
Environment Variables From dotenv
Environment Variables From virtualenv
Custom Commands
Plugins
Custom Scripts
PyCharm Integration
Development Server
Command Line
In Code
Working with the Shell
Command Line Interface
Creating a Request Context
Firing Before/After Request
Further Improving the Shell Experience
Patterns for Flask
Larger Applications
Application Factories
Application Dispatching
Implementing API Exceptions
Using URL Processors
Deploying with Setuptools
Deploying with Fabric
Using SQLite 3 with Flask
SQLAlchemy in Flask
Uploading Files
Caching
View Decorators
Form Validation with WTForms
Template Inheritance
Message Flashing
AJAX with jQuery
Custom Error Pages
Lazily Loading Views
MongoDB with MongoEngine
Adding a favicon
Streaming Contents
Deferred Request Callbacks
Adding HTTP Method Overrides
Request Content Checksums
Celery Background Tasks
Subclassing Flask
Single-Page Applications
Deployment Options
Hosted options
Self-hosted options
Becoming Big
Read the Source.
Hook. Extend.
Subclass.
Wrap with middleware.
Fork.
Scale like a pro.
Discuss with the community.
API Reference
If you are looking for information on a specific function, class or method, this part of the documentation is for you.
API
Application Object
Blueprint Objects
Incoming Request Data
Response Objects
Sessions
Session Interface
Test Client
Test CLI Runner
Application Globals
Useful Functions and Classes
Message Flashing
JSON Support
Template Rendering
Configuration
Stream Helpers
Useful Internals
Signals
Class-Based Views
URL Route Registrations
View Function Options
Command Line Interface
Additional Notes
Design notes, legal information and changelog are here for the interested.
Design Decisions in Flask
The Explicit Application Object
The Routing System
One Template Engine
Micro with Dependencies
Thread Locals
What Flask is, What Flask is Not
HTML/XHTML FAQ
History of XHTML
History of HTML5
HTML versus XHTML
What does “strict” mean?
New technologies in HTML5
What should be used?
Security Considerations
Cross-Site Scripting (XSS)
Cross-Site Request Forgery (CSRF)
JSON Security
Security Headers
Copy/Paste to Terminal
Unicode in Flask
Automatic Conversion
The Golden Rule
Encoding and Decoding Yourself
Configuring Editors
Flask Extension Development
Anatomy of an Extension
“Hello Flaskext!”
Initializing Extensions
The Extension Code
Using _app_ctx_stack
Learn from Others
Approved Extensions
Pocoo Styleguide
General Layout
Expressions and Statements
Naming Conventions
Docstrings
Comments
Upgrading to Newer Releases
Version 0.12
Version 0.11
Version 0.10
Version 0.9
Version 0.8
Version 0.7
Version 0.6
Version 0.5
Version 0.4
Version 0.3
Changelog
Version 1.1.x
Version 1.1.2
Version 1.1.1
Version 1.1.0
Version 1.0.4
Version 1.0.3
Version 1.0.2
Version 1.0.1
Version 1.0
Version 0.12.5
Version 0.12.4
Version 0.12.3
Version 0.12.2
Version 0.12.1
Version 0.12
Version 0.11.1
Version 0.11
Version 0.10.1
Version 0.10
Version 0.9
Version 0.8.1
Version 0.8
Version 0.7.2
Version 0.7.1
Version 0.7
Version 0.6.1
Version 0.6
Version 0.5.2
Version 0.5.1
Version 0.5
Version 0.4
Version 0.3.1
Version 0.3
Version 0.2
Version 0.1
License
Source License
Artwork License
How to contribute to Flask
Support questions
Reporting issues
Submitting patches
Caution: zero-padded file modes
Project Links
Donate to Pallets
Flask Website
PyPI releases
Source Code
Issue Tracker
Contents
Welcome to Flask
User’s Guide
API Reference
Additional Notes
Quick search
Introducing App Platform a new PaaS that gets your apps to market, faster. Try Now with $100 Credit.
Sponsored · Ads served ethically
<file_sep>from flask import Flask,render_template,request
# creating an object
app=Flask(__name__)
fruits=['apple','orange','banana']
# creating a route
@app.route('/')
def main():
return render_template('fruits.html',my_fruits=fruits)
@app.route('/submit',methods=['POST'])
def submit():
#return 'you are on submit page'
if request.method=='POST':
name=request.form['username']
f=request.files['userfile']
#print(f)
f.save(f.filename)
return '<h2>Hello {}'.format(name)
if __name__ == '__main__':
app.run(debug=True)
| d585050d07c630c22819dd47e59075c43d1ba6b1 | [
"Markdown",
"Python"
] | 3 | Python | grand-27-master/Get-started-with-Flask | ef87935e45a688f6f81aada4972926e484763e68 | 830152179ee2422947ae6aad34ce975b84706c7d |
refs/heads/master | <file_sep>//-----------@Author by UlucFurkanVardar
#include <SharpIR.h> //IR Sharp sensörü kullanabilmek için kullandığımız kütüphane, bu kütüphaneyi kütüphane düzenleyicisinden indirebilir.
#include <Servo.h> //Servoları kullanabilmek için gerekli olan kütüphane
SharpIR sensor(GP2Y0A21YK0F, A0); // IRSharptan bir sensör objesi tanımladık ve bu markanın üç farklı ürününü ayırt edebilmek için elimizde olan ürünün data sheetindeki ID sini kullandık.
Servo LeftWheel; //Continues servoları kullanırken Sol tarafta 90-180 arası ileri aracı ileri götürecektir.
Servo RightWheel; //Continues servoları kullanırken Sag tarafta 0-90 arası ileri aracı ileri götürecektir.
//Projemizde arduino pro mini kullanıyoruz ve giriş çıkış pinlerini hangi pine neyin takıldığını anlayabilmek için pinlerimize isim vererek devam ediyoruz.
const int BuzzerPin = 3;
const int ButtonPin = 2;
const int LeftSensor = 4;
const int CenterSensor = 7;
const int RightSensor = 8;
const int LeftServoPin = 5;
const int RightServoPin = 6;
// Kod boyunca kullandığımız gereki olan değişkenler.
int distance = 0; //IR sharp sensörün mesafe ayarlaması için.
int ButtonCounter = 0; //Açılışta modu ayarlayabilmemizi sağlayan Butonunn tıklanmasını sayan counter.
int LeftS = 0; //çizgi izleme modülünün gerekli değişkenleri.
int CenterS = 0;
int RightS = 0; // 0 siyahı, 1 beyazı temsil ediyor.
//Buzzerın notaları için gerekli olanlar.
int Number_of_notes = 8;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int C_ = 523;
int notalar[] = {C, D, E, F, G, A, B, C_};
void setup() {
Serial.begin(9600); //PinMode ve Serial ayarlamaları.
pinMode(ButtonPin, INPUT);
pinMode(13, OUTPUT);
pinMode(RightSensor, INPUT);
pinMode(CenterSensor, INPUT);
pinMode(LeftSensor, INPUT);
digitalWrite(13, LOW);
digitalWrite(ButtonPin, HIGH);
LeftWheel.attach(LeftServoPin); //Servo tanımlamarı.
RightWheel.attach(RightServoPin);
delay(600);
if ( digitalRead(ButtonPin) == 0) {//açılışta buyona tıklanmasuını sayan eğer tıklanma sayılırsa 13. gömülü olan led bir şere yanıp sönecek ve bir melodi çalacak.
ButtonCounter++;
digitalWrite(13, HIGH);
delay(50);
digitalWrite(13, LOW);
tone(BuzzerPin, notalar[0]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
delay(500);
if (digitalRead(ButtonPin) == 0) {//açılışta buyona tıklanmasuını sayan eğer tıklanma sayılırsa 13. gömülü olan led bir şere yanıp sönecek ve bir melodi çalacak.
ButtonCounter++;
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
tone(BuzzerPin, notalar[1]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
Serial.print("Buton Counter : "); //kontrol amaçlı ButtonCounter ekrana basılıyor.
Serial.println(ButtonCounter);
delay(1000);
}
void loop() {
if (ButtonCounter == 1) { //Eğer bir kere tıklandı ise çizgi izleme modunda araç çalışacak.
line_tracking();
}
else if (ButtonCounter == 2) { //iki kere tıklandıysa otonom sürüş modunda çalışacak.
autonomous_driving();
}
else if (ButtonCounter == 0) { //tıklanmadan açıldıysa çizgi izlerken önüne engel çıkarsa durarak çalışacak.
autonomous_Line_tracking();
}
else { //aksi halde gömülü led yanığ sönecek araç duracak ve tüm meledilerini sıra ile çalacak.
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
RightWheel.write(90);
LeftWheel.write(95);
for (int i = 0; i < Number_of_notes; i++)
{
tone(BuzzerPin, notalar[i]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
noTone(BuzzerPin);
}
if (digitalRead(ButtonPin) == 0) { //araç ilerler haldeysen butona tıklanırsa araç duracak ve melodi çalmaya başlıyacak.
ButtonCounter = 5;
}
}
void autonomous_Line_tracking() {
distance = sensor.getDistance();
if (distance > 12) {
line_tracking();
noTone(BuzzerPin);
}
else {
RightWheel.write(90);
LeftWheel.write(95);
tone(BuzzerPin, notalar[7]);
delay(200);
}
}
void autonomous_driving() {
/*
otonom ilerlemenin mantığı nedir?
basit bir şekilde önüne engel çıktığında o yönde ilerlemeyi bırakması.
ardından hangi tarafa döneceiğinin mantıklı kararını verme.
bir tarafa dönüş başlatma taki önü açılana dek.
Bizim robotumuzun yanlarında başka sensörleri olmadığı için mantıklı karar yerine biz aracımızı sola göndürüyoruz.
*/
distance = sensor.getDistance(); // eklediğimiz kütüphaneden yararlanark daha önce mesafe hesaplamaya yarayan fonksiyonu çağırıyoruz.
if (distance <= 12) { // mesafenin 12ye eşit veya kücük olduğu durumlarda aracamız dönüyor.
RightWheel.write(50);
LeftWheel.write(95);
}
else { // aksi halde düz gitmeye devam ediyor.
LeftWheel.write(130);
RightWheel.write(50);
}
}
void line_tracking() {
/*
çizgi izlemenin mantığı nedir?
bir robot çizgi izlemesi için programlanırken düşünülmesi gereken çizgiden ÇIKTIĞI anlardır
çıktı anlar düzeltilmedilir.
eğer doğru düzeltmeler yapılırsa robor çizgiyi takip ederek ilerlemeye devam edecektir.
bu durumda robotun çizgiden çıkmaya başladığı durumları sensörlerimizle değerlendirmeliyiz.
*/
LeftS = digitalRead(LeftSensor);
CenterS = digitalRead(CenterSensor);
RightS = digitalRead(RightSensor);
//her bir loop turunda güncel sensör verileri alnmalı
// 1 . soldan çizgiden çıkar ise
if (LeftS == 1 && RightS == 0 ) {
//sag dön
LeftWheel.write(130);
RightWheel.write(90);
}
//2. sagdan çizgiden çıkıyor ise
else if (RightS == 1 && LeftS == 0 ) {
//sola dön
RightWheel.write(50);
LeftWheel.write(95);
}
//Aksi halde aracın düz gitmesi gerekiyor.
else {
LeftWheel.write(130);
RightWheel.write(50);
}
}
<file_sep># Mini Autonomous Car
In these project, an arduino rule based autonomous car was created. The vehicle has three capabilities.
- watch line

- escape from obstacles

- watch line (when there is an obstacles on the road stop)

#### Code is also loaded here. will be updated as soon as possible with English explanations!
```c
//-----------@Author by UlucFurkanVardar
#include <SharpIR.h> //IR Sharp sensörü kullanabilmek için kullandığımız kütüphane, bu kütüphaneyi kütüphane düzenleyicisinden indirebilir.
#include <Servo.h> //Servoları kullanabilmek için gerekli olan kütüphane
SharpIR sensor(GP2Y0A21YK0F, A0); // IRSharptan bir sensör objesi tanımladık ve bu markanın üç farklı ürününü ayırt edebilmek için elimizde olan ürünün data sheetindeki ID sini kullandık.
Servo LeftWheel; //Continues servoları kullanırken Sol tarafta 90-180 arası ileri aracı ileri götürecektir.
Servo RightWheel; //Continues servoları kullanırken Sag tarafta 0-90 arası ileri aracı ileri götürecektir.
//Projemizde arduino pro mini kullanıyoruz ve giriş çıkış pinlerini hangi pine neyin takıldığını anlayabilmek için pinlerimize isim vererek devam ediyoruz.
const int BuzzerPin = 3;
const int ButtonPin = 2;
const int LeftSensor = 4;
const int CenterSensor = 7;
const int RightSensor = 8;
const int LeftServoPin = 5;
const int RightServoPin = 6;
// Kod boyunca kullandığımız gereki olan değişkenler.
int distance = 0; //IR sharp sensörün mesafe ayarlaması için.
int ButtonCounter = 0; //Açılışta modu ayarlayabilmemizi sağlayan Butonunn tıklanmasını sayan counter.
int LeftS = 0; //çizgi izleme modülünün gerekli değişkenleri.
int CenterS = 0;
int RightS = 0; // 0 siyahı, 1 beyazı temsil ediyor.
//Buzzerın notaları için gerekli olanlar.
int Number_of_notes = 8;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int C_ = 523;
int notalar[] = {C, D, E, F, G, A, B, C_};
void setup() {
Serial.begin(9600); //PinMode ve Serial ayarlamaları.
pinMode(ButtonPin, INPUT);
pinMode(13, OUTPUT);
pinMode(RightSensor, INPUT);
pinMode(CenterSensor, INPUT);
pinMode(LeftSensor, INPUT);
digitalWrite(13, LOW);
digitalWrite(ButtonPin, HIGH);
LeftWheel.attach(LeftServoPin); //Servo tanımlamarı.
RightWheel.attach(RightServoPin);
delay(600);
if ( digitalRead(ButtonPin) == 0) {//açılışta buyona tıklanmasuını sayan eğer tıklanma sayılırsa 13. gömülü olan led bir şere yanıp sönecek ve bir melodi çalacak.
ButtonCounter++;
digitalWrite(13, HIGH);
delay(50);
digitalWrite(13, LOW);
tone(BuzzerPin, notalar[0]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
delay(500);
if (digitalRead(ButtonPin) == 0) {//açılışta buyona tıklanmasuını sayan eğer tıklanma sayılırsa 13. gömülü olan led bir şere yanıp sönecek ve bir melodi çalacak.
ButtonCounter++;
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
tone(BuzzerPin, notalar[1]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
Serial.print("Buton Counter : "); //kontrol amaçlı ButtonCounter ekrana basılıyor.
Serial.println(ButtonCounter);
delay(1000);
}
void loop() {
if (ButtonCounter == 1) { //Eğer bir kere tıklandı ise çizgi izleme modunda araç çalışacak.
line_tracking();
}
else if (ButtonCounter == 2) { //iki kere tıklandıysa otonom sürüş modunda çalışacak.
autonomous_driving();
}
else if (ButtonCounter == 0) { //tıklanmadan açıldıysa çizgi izlerken önüne engel çıkarsa durarak çalışacak.
autonomous_Line_tracking();
}
else { //aksi halde gömülü led yanığ sönecek araç duracak ve tüm meledilerini sıra ile çalacak.
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
RightWheel.write(90);
LeftWheel.write(95);
for (int i = 0; i < Number_of_notes; i++)
{
tone(BuzzerPin, notalar[i]);
delay(500);
noTone(BuzzerPin);
delay(20);
}
noTone(BuzzerPin);
}
if (digitalRead(ButtonPin) == 0) { //araç ilerler haldeysen butona tıklanırsa araç duracak ve melodi çalmaya başlıyacak.
ButtonCounter = 5;
}
}
void autonomous_Line_tracking() {
distance = sensor.getDistance();
if (distance > 12) {
line_tracking();
noTone(BuzzerPin);
}
else {
RightWheel.write(90);
LeftWheel.write(95);
tone(BuzzerPin, notalar[7]);
delay(200);
}
}
void autonomous_driving() {
/*
otonom ilerlemenin mantığı nedir?
basit bir şekilde önüne engel çıktığında o yönde ilerlemeyi bırakması.
ardından hangi tarafa döneceiğinin mantıklı kararını verme.
bir tarafa dönüş başlatma taki önü açılana dek.
Bizim robotumuzun yanlarında başka sensörleri olmadığı için mantıklı karar yerine biz aracımızı sola göndürüyoruz.
*/
distance = sensor.getDistance(); // eklediğimiz kütüphaneden yararlanark daha önce mesafe hesaplamaya yarayan fonksiyonu çağırıyoruz.
if (distance <= 12) { // mesafenin 12ye eşit veya kücük olduğu durumlarda aracamız dönüyor.
RightWheel.write(50);
LeftWheel.write(95);
}
else { // aksi halde düz gitmeye devam ediyor.
LeftWheel.write(130);
RightWheel.write(50);
}
}
void line_tracking() {
/*
çizgi izlemenin mantığı nedir?
bir robot çizgi izlemesi için programlanırken düşünülmesi gereken çizgiden ÇIKTIĞI anlardır
çıktı anlar düzeltilmedilir.
eğer doğru düzeltmeler yapılırsa robor çizgiyi takip ederek ilerlemeye devam edecektir.
bu durumda robotun çizgiden çıkmaya başladığı durumları sensörlerimizle değerlendirmeliyiz.
*/
LeftS = digitalRead(LeftSensor);
CenterS = digitalRead(CenterSensor);
RightS = digitalRead(RightSensor);
//her bir loop turunda güncel sensör verileri alnmalı
// 1 . soldan çizgiden çıkar ise
if (LeftS == 1 && RightS == 0 ) {
//sag dön
LeftWheel.write(130);
RightWheel.write(90);
}
//2. sagdan çizgiden çıkıyor ise
else if (RightS == 1 && LeftS == 0 ) {
//sola dön
RightWheel.write(50);
LeftWheel.write(95);
}
//Aksi halde aracın düz gitmesi gerekiyor.
else {
LeftWheel.write(130);
RightWheel.write(50);
}
}
```
| 580d87791af581e61d5d30cece440cb27a9fea50 | [
"Markdown",
"C++"
] | 2 | C++ | UlucFVardar/3D-printed-Mini-Autonomous-Car | 32f5db2565f7b64d21785016ba554335386a9816 | 089587bcb6d6ca0d5c3960da6e8b2aa694105d30 |
refs/heads/master | <repo_name>crokadilekyle/node-js-crash-course<file_sep>/reference/path_demo.js
const path = require("path");
//basename() - returns base file name from the path
console.log(path.basename(__filename));
console.log(path.dirname(__filename));
console.log(__dirname);
// //extname() - returns file extension
console.log(path.extname(__filename));
//create path object
console.log(path.parse(__filename).base);
//concatenate paths
console.log(path.join(__dirname, "test", "hello.html"));
<file_sep>/reference/fs_demo.js
const fs = require("fs");
const path = require("path");
//create folder
// fs.mkdir(path.join(__dirname, "test"), {}, function(err) {
// if (err) throw err;
// console.log("folder created");
// });
//create file
// fs.writeFile(
// path.join(__dirname, "test", "hello.html"),
// "<h1>Node is cool</h1>\r",
// err => {
// if (err) throw err;
// console.log("file created");
// fs.appendFile(
// path.join(__dirname, "test", "hello.html"),
// "<h2>I think</h2>\r",
// err => {
// if (err) throw err;
// console.log("file appended to");
// }
// );
// }
// );
//read file
// fs.readFile(
// path.join(__dirname, "/test", "hello.html"),
// "utf8",
// (err, data) => {
// if (err) throw err;
// console.log(data);
// }
// );
//rename file
fs.rename(path.join(__dirname, "/test", "hello.html"), "index.html", err => {
if (err) throw err;
console.log("file name changed");
});
<file_sep>/reference/url_demo.js
const url = require("url");
const myUrl = new URL("https://kylemerl.com/?project=websites");
// Serialized URL
console.log(myUrl.href);
console.log(myUrl.toString());
//Host (root domain)
console.log(myUrl.host);
//Does not get port #
console.log(myUrl.hostname);
//Gets file
console.log(myUrl.pathname);
//Get Search parameters
console.log(myUrl.search);
//Get search parameters object
console.log(myUrl.searchParams);
myUrl.searchParams.append("abc", "123");
console.log(myUrl.searchParams);
myUrl.searchParams.forEach((value, name) => console.log(value, name));
| cbb9bcb6ad48133375c2b637fbaec1643dea9b1b | [
"JavaScript"
] | 3 | JavaScript | crokadilekyle/node-js-crash-course | 462b707a8e426d4cb6e0308821c4fd424cda3b22 | 9a2fa2478313a930a06f4b969c4a635d518bf063 |
refs/heads/master | <repo_name>RicardoR22/Balloon-Math<file_sep>/README.md
# Balloon-Math
I created this game because I wanted kids to have something more productive to play.
This game aims to help kids become better at basic addition, while at the same time allowing them to have fun.
How to play:
You will be prompted with a simple addition problem.
Two clouds with possible answers will appear.
Choose the correct answer to gain a point!
Choose the wrong answer and your score is reset back to 0
<file_sep>/Balloon Math/Balloon Math/CreateBalloon.swift
//
// CreateBalloon.swift
// Balloon Math
//
// Created by <NAME> on 10/15/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import SpriteKit
//Class for creating Balloon
class Balloon: SKSpriteNode {
init(scene: SKScene) {
let texture = SKTexture(imageNamed: "Balloon")
let size = CGSize(width: 50, height: 50)
super.init(texture: texture, color: .red, size: size)
self.name = "balloon"
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented")}
}
<file_sep>/Balloon Math/Balloon Math/GameScene.swift
//
// GameScene.swift
// Balloon Math
//
// Created by <NAME> on 10/15/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var balloon : Balloon?
var cloud1 : Cloud?
var cloud2 : Cloud?
var questionLabel = SKLabelNode(fontNamed: "Optima-Bold")
var timerLabel = SKLabelNode(fontNamed: "Optima-Bold")
var timeLabel = SKLabelNode(fontNamed: "Optima-Bold")
var scoreLabel = SKLabelNode(fontNamed: "Optima-Bold")
var scoreText = SKLabelNode(fontNamed: "Optima-Bold")
var timer = Timer()
var expectingInput = true
var arg1: Int?
var arg2: Int?
var answer1 = 0
var answer2 = 0
var score = 0
var timeLimit = 5
override func didMove(to view: SKView) {
self.gameLoop()
}
// Function that handles creating the balloon
func createBalloon() {
// Creates instance of Balloon Class
if balloon == nil {
balloon = Balloon(scene: self)
} else {
balloon?.removeFromParent()
balloon = Balloon(scene: self)
}
if let view = self.view {
// Action for making balloon "float" up
let moveUp = SKAction.moveBy(x: 0.00, y: view.bounds.height/4, duration: 2.0)
if let balloon = balloon {
// Positions Balloon at center of screen, horizontally
balloon.position.x = view.bounds.width/2 - balloon.size.width/2
// Positions Balloon at bottom of screen
balloon.position.y = 0
balloon.run(moveUp)
}
}
if balloon?.parent == nil {
addChild(balloon!)
}
}
// Function that handles creating the clouds
func createClouds() {
// Created instances of Cloud class
if (cloud1 == nil) && (cloud2 == nil) {
cloud1 = Cloud(scene: self, answer: answer1)
cloud2 = Cloud(scene: self, answer: answer2)
} else {
cloud1?.removeFromParent()
cloud2?.removeFromParent()
cloud1 = Cloud(scene: self, answer: answer1)
cloud2 = Cloud(scene: self, answer: answer2)
}
if let view = self.view {
// Actions for making clouds come down
let moveDown = SKAction.moveBy(x: 0.00, y: -view.bounds.height/3, duration: 2.0)
if let cloud1 = cloud1 {
if let cloud2 = cloud2 {
// Set Cloud properties
cloud1.position.x = CGFloat(0 + (cloud1.size.width/2))
cloud1.position.y = size.height
cloud1.zPosition = 2
cloud2.position.x = CGFloat(view.bounds.width - (cloud1.size.width - 15))
cloud2.position.y = size.height
cloud2.zPosition = 2
cloud1.run(moveDown)
cloud2.run(moveDown)
}
}
if cloud1?.parent == nil && cloud2?.parent == nil {
addChild(cloud1!)
addChild(cloud2!)
}
}
}
// Function that handles creating the math problem
func createProblem() {
// generate 2 random integers
arg1 = Int.random(in: 5...10)
arg2 = Int.random(in: 5...10)
if let arg1 = arg1{
if let arg2 = arg2 {
// Display the problem. Integer1 + Integer2
questionLabel.text = ("\(arg1) + \(arg2)")
}
}
// Set properties for the label displaying the problem
if let view = self.view{
questionLabel.fontSize = 30
questionLabel.fontColor = .black
questionLabel.position.x = view.bounds.width/2 - 30
questionLabel.position.y = view.bounds.height/1.5
}
if questionLabel.parent == nil {
addChild(questionLabel)
}
}
// Function that handles creating the responses for the question
func createResponses() {
// Chooses a random cloud to hold the correct answer
let correctCloud = Int.random(in: 1...2)
guard let arg1 = arg1 else {
print("No Argument 1")
return
}
guard let arg2 = arg2 else {
print("No Argument 2")
return
}
// Assigns the answer values to each cloud.
if correctCloud == 1 {
// One gets the correct answer, the other get a random answer.
answer1 = arg1 + arg2
answer2 = Int.random(in: 5...10) + Int.random(in: 5...9)
if answer1 == answer2 {
answer2 = Int.random(in: 5...10) + Int.random(in: 5...9)
}
} else {
answer2 = arg1 + arg2
answer1 = Int.random(in: 5...10) + Int.random(in: 5...9)
if answer1 == answer2 {
answer1 = Int.random(in: 5...10) + Int.random(in: 5...9)
}
}
}
// Timer function
func countdown() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ t in
self.timeLimit -= 1
self.timerLabel.text = String(self.timeLimit)
// Checks if time is up
if self.timeLimit == 0 {
// Stop timer
t.invalidate()
// Notify that time is up
self.questionLabel.text = "Times up!"
self.loseAnimations()
self.score = 0
self.timeLimit = 5
// Restart game after a short delay
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.gameLoop()
}
}
}
}
// The game loop. Responsible for keeping the game running
func gameLoop() {
if let view = self.view{
timerLabel.fontSize = 15
timerLabel.fontColor = .black
timerLabel.position.x = view.bounds.width - 80
timerLabel.position.y = view.bounds.height - 150
timerLabel.text = String(timeLimit)
scoreLabel.fontSize = 15
scoreLabel.fontColor = .black
scoreLabel.position.x = 30
scoreLabel.position.y = view.bounds.height - 130
scoreLabel.text = "Score"
scoreText.fontSize = 15
scoreText.fontColor = .black
scoreText.position.x = 30
scoreText.position.y = view.bounds.height - 150
scoreText.text = String(score)
timeLabel.fontSize = 15
timeLabel.fontColor = .black
timeLabel.position.x = view.bounds.width - 85
timeLabel.position.y = view.bounds.height - 130
timeLabel.text = "Time"
}
if timerLabel.parent == nil {
addChild(scoreLabel)
addChild(scoreText)
addChild(timeLabel)
addChild(timerLabel)
}
createBalloon()
createProblem()
createResponses()
createClouds()
// Start timer
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.expectingInput = true
self.countdown()
}
}
// Checks the users answer
func checkAnswer(node: Cloud) {
guard let arg1 = arg1 else {
print("No Argument 1")
return
}
guard let arg2 = arg2 else {
print("No Argument 2")
return
}
if node.answerValue == arg1 + arg2 {
questionLabel.text = "Correct!"
score += 1
winAnimations()
} else {
questionLabel.text = "Wrong"
loseAnimations()
score = 0
timeLimit = 5
}
}
// Animations that are used when you get the correct answer
func winAnimations() {
guard let view = self.view else{
return
}
guard let balloon = balloon else {
return
}
guard let cloud1 = cloud1 else {
return
}
guard let cloud2 = cloud2 else {
return
}
// SKActions for answer animations
let balloonFloatUp = SKAction.moveBy(x: 0.00, y: view.bounds.height, duration: 2.0)
let moveDown = SKAction.moveBy(x: 0.00, y: -view.bounds.height, duration: 2.0)
let remove = SKAction.removeFromParent()
let balloonWinSeq = SKAction.sequence([balloonFloatUp, remove])
let cloudWinSeq = SKAction.sequence([moveDown, remove])
balloon.run(balloonWinSeq)
cloud1.run(cloudWinSeq)
cloud2.run(cloudWinSeq)
}
// Animations that are used when you don't get the correct answer
func loseAnimations() {
guard let view = self.view else{
return
}
guard let balloon = balloon else {
return
}
guard let cloud1 = cloud1 else {
return
}
guard let cloud2 = cloud2 else {
return
}
// SKActions for answer animations
let balloonFloatDown = SKAction.moveBy(x: 0.00, y: -view.bounds.height, duration: 2.0)
let moveUp = SKAction.moveBy(x: 0.00, y: view.bounds.height, duration: 2.0)
let scaleDown = SKAction.scale(by: -0.5, duration: 2.0)
let remove = SKAction.removeFromParent()
let cloudLoseSeq = SKAction.sequence([moveUp, remove])
let balloonLoseGroup = SKAction.group([balloonFloatDown, scaleDown])
let balloonLoseSeq = SKAction.sequence([balloonLoseGroup, remove])
balloon.run(balloonLoseSeq)
cloud1.run(cloudLoseSeq)
cloud2.run(cloudLoseSeq)
}
// Handles the detection of a touch on a cloud
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let location = touch.location(in: self)
let node = atPoint(location)
if node.name == "cloud" && expectingInput == true {
expectingInput = false
// Moves balloon to cloud that was touched
let moveToCloud = SKAction.move(to: location, duration: 1)
balloon?.run(moveToCloud)
self.timer.invalidate()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.checkAnswer(node: node as! Cloud)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.timeLimit = 5
self.gameLoop()
}
}
}
}
<file_sep>/Balloon Math/Balloon Math/CreateCloud.swift
//
// CreateCloud.swift
// Balloon Math
//
// Created by <NAME> on 10/15/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import SpriteKit
//Class for creating Clouds
class Cloud: SKSpriteNode {
var answerValue: Int
var answerLabel = SKLabelNode(text: "2")
init(scene: SKScene, answer: Int) {
let texture = SKTexture(imageNamed: "cloud")
let size = CGSize(width: 150, height: 90)
self.answerValue = answer
super.init(texture: texture, color: .red, size: size)
self.name = "cloud"
answerLabel.zPosition = 10
answerLabel.horizontalAlignmentMode = .center
answerLabel.verticalAlignmentMode = .center
answerLabel.fontName = "Optima-Bold"
answerLabel.fontColor = .black
answerLabel.text = String(self.answerValue)
addChild(answerLabel)
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented")}
}
| d9fe37dd2913d142e6ee972677cfca2d717f0017 | [
"Markdown",
"Swift"
] | 4 | Markdown | RicardoR22/Balloon-Math | 5922350d24a090260b6ed0e12b9fb67d549fe37f | 75d6baea424dd9856c374033e6514c458cf5b3f8 |
refs/heads/master | <file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
from werkzeug import generate_password_hash, check_password_hash
import python.database_static as database_static
import mysql.connector
def returnTable(id_u):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT Nazwa, Zlacze, Pin,data_utw,Godzina_podl,data_podlewania,okr_podl from `Flowers` WHERE id_u="+str(id_u)
r=cursor.execute(query)
result=cursor.fetchall()
count = cursor.rowcount
cursor.close()
cnx.close()
return result
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def returnTable2(id_u):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT id_f, Nazwa, Zlacze, Pin from `Flowers` WHERE id_u="+str(id_u)
r=cursor.execute(query)
result=cursor.fetchall()
count = cursor.rowcount
cursor.close()
cnx.close()
return result
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
import python.database_static as database_static
import mysql.connector
def addSecs(tm, secs):
fulldate = datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + timedelta(seconds=secs)
return fulldate.time()
def nawadnianie(listaFlowers,lista):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
add_user = ("INSERT INTO `Irrigation` "
"(id_f, Nazwa, Zlacze, Pin, godz_wyk) "
"VALUES (%s, %s, %s, %s,%s)")
a = datetime.now().time()
sec=0
for i in range(len(listaFlowers)):
for j in range(len(lista)):
if(i==int(lista[j])):
b = addSecs(a, 600+sec)
data_employee = (str(listaFlowers[i][0]), listaFlowers[i][1],listaFlowers[i][2],str(listaFlowers[i][3]) ,b)
result=cursor.execute(add_user, data_employee)
sec+=60
cnx.commit()
cursor.close()
cnx.close()
return 2
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from datetime import date, datetime, timedelta
import python.database_static as database_static
import mysql.connector
def returnTable():
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT id_f, Nazwa, Zlacze, Pin,data_podlewania,okr_podl from `Flowers`"
r=cursor.execute(query)
result=cursor.fetchall()
count = cursor.rowcount
cursor.close()
cnx.close()
return result
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def updateTable(id_f,name):
try:
print(id_f,name)
cnx = database_static.connecting()
cursor = cnx.cursor()
query="UPDATE `Flowers` SET data_podlewania=%s WHERE id_f=%s AND Nazwa=%s"
today = datetime.now()
b = today + timedelta(seconds=300)
db=datetime.strptime(str(b.date())+" "+str(b.hour)+":"+str(b.minute),'%Y-%m-%d %H:%M')
datetm=(db,id_f,name)
r=cursor.execute(query,datetm)
cnx.commit()
cursor.close()
cnx.close()
return 2
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def saveHistory(id_f,old_date,new_date):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
add_user = ("INSERT INTO `History` "
"(id_f, data_podlewania, data_nast_podl) "
"VALUES (%s, %s, %s)")
data_employee = (id_f, old_date,new_date)
result=cursor.execute(add_user, data_employee)
print(result)
cnx.commit()
cursor.close()
cnx.close()
return 2
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep> /*function chooseBoard(idNumber){
document.getElementById("toAnotherSelect").innerHTML = idNumber;
document.getElementById("mySelect").options.length = 0
var x = document.getElementById("mySelect");
var length = x.options.length;
if(idNumber ==0){
var c = document.createElement("option");
c.text = "--NONE--";
x.options.add(c, 0);
}else if(idNumber==1){
for(i=0;i<20;i++){
var c = document.createElement("option");
c.text = i;
x.options.add(c, i);
}
}else{
for(i=0;i<8;i++){
var c = document.createElement("option");
c.text = i;
x.options.add(c, i);
}
}
document.getElementById("toAnotherSelect").innerHTML = length;
}*/
function chooseBoard(idNumber){
//document.getElementById("toAnotherSelect").innerHTML = idNumber;
var x = document.getElementById("pin");
var len = x.options.length;
for(var i=len-1;i>=0;i--){
x.options[i]=null;
}
if(idNumber == 0){
var c = document.createElement("option");
c.text = "--NONE--";
x.options.add(c, 0);
}else if(idNumber==1){
for(i=0;i<20;i++){
var c = document.createElement("option");
c.text = i;
x.options.add(c, i);
}
}else{
for(i=0;i<8;i++){
var c = document.createElement("option");
c.text = i;
x.options.add(c, i);
}
}
len = x.options.length; //aktualna dlugosc
//document.getElementById("toAnotherSelect").innerHTML = len;
}
function checkAll(){
var checkBoxAll = document.getElementsByName("selectAll")[0];
var checkBoxSelect = document.getElementsByName("selectThis[]");
if(checkBoxAll.checked == false){
for(var i=0;i<checkBoxSelect.length;i++){
checkBoxSelect[i].checked = false;
}
}
else{
for(var i=0;i<checkBoxSelect.length;i++){
checkBoxSelect[i].checked = true;
}
}
}
<file_sep>from flask import Flask, render_template, flash, request, redirect, url_for, session
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from werkzeug import generate_password_hash, check_password_hash
import random, threading, webbrowser
import time
from threading import Thread, Event
from datetime import date, datetime, timedelta
import wiringpi as wiringpi
import RPi.GPIO as GPIO
import sys
sys.path.insert(0, '/home/arhelius/flask')
import python.sign_up as sign_up, python.login as login, python.addflower as addflower, python.table_flower as tf, python.deleteFlower as df,python.irrigation as ir, python.history as his
import python.I2C_LCD_driver as I2C_LCD_driver, python.tables_operations as to
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.OUT)
GPIO.output(17,1)
mylcd = I2C_LCD_driver.lcd()
change_class=1
pin_base=65
i2c_addr=0x20
wiringpi.wiringPiSetup()
wiringpi.pcf8574Setup(pin_base,i2c_addr)
def loop_process():
global change_class
example=0
flow=None
while True:
now=datetime.now()
if (change_class==1 or example==1):
flow=to.returnTable()
change_class=0
example=0
print(flow)
for i in range(len(flow)):
if(flow[i][4].year<=now.year and flow[i][4].month<=now.month and flow[i][4].day<=now.day and flow[i][4].hour<=now.hour and flow[i][4].minute<=now.minute):
temp=flow[i][4]
tonight=datetime.now()+timedelta(seconds=300)
if(to.updateTable(flow[i][0],flow[i][1])>0):
if(to.saveHistory(flow[i][0],temp,tonight)>0):
mylcd.lcd_clear()
GPIO.output(17,0)
mylcd.lcd_display_string("Trwa podlewanie", 1)
mylcd.lcd_display_string("Kwiatek: %s" %flow[i][1], 2)
wiringpi.digitalWrite(65+int(flow[i][3]),0)
time.sleep(10)
mylcd.lcd_clear()
wiringpi.digitalWrite(65+int(flow[i][3]),1)
GPIO.output(17,1)
example=1
print(now)
mylcd.lcd_display_string("Time: %s" %time.strftime("%H:%M:%S"), 1)
mylcd.lcd_display_string("Date: %s" %time.strftime("%m/%d/%Y"), 2)
time.sleep(1)
thread = threading.Thread(target=loop_process)
app = Flask(__name__)
port = 5000
url = "http://127.0.0.1:{0}".format(port)
def startTime():
seconds=datetime.now().strftime("%S")
print(seconds)
@app.route("/",methods=['GET', 'POST'])
def main():
if(session.get('logged_in')==True):
session.clear()
form = login.ReusableForm(request.form)
print(form.errors)
if request.method == 'POST':
name=request.form['name']
password=request.form['<PASSWORD>']
if form.validate():
if(login.login(name,password)>1):
session['logged_in'] = True
session['id_u']=login.setId(name,password)
print(session['id_u'])
return redirect(url_for('menu'))
elif(login.login(name,password)==1):
flash('Error: Podano złe hasło ')
else:
flash('Error: Nie ma takiego użytkownika ')
else:
flash('Error: Wszystkie pola muszą być wypełnione ')
return render_template('index.html',form=form)
@app.route("/menu")
def menu():
if(session.get('logged_in')==True):
startTime()
table=tf.returnTable(session['id_u'])
print(table)
return render_template('menu.html',table=table)
else:
return redirect(url_for('main'))
@app.route("/edycja")
def edycja():
if(session.get('logged_in')==True):
table=tf.returnTable(session['id_u'])
return render_template('edition.html',table=table)
else:
return redirect(url_for('main'))
@app.route("/edycja/usun",methods=['GET', 'POST'])
def usun_kwiatka():
global change_class
if(session.get('logged_in')==True):
table=tf.returnTable(session['id_u'])
lista=request.form.getlist('selectThis[]')
if(df.delete_flower(table,lista)==2 and lista!=[]):
flash('Success: Usunieto kwiaty z bazy danych')
change_class=1
return redirect(url_for('edycja'))
elif(lista==[]):
return render_template('deleteFlower.html',table=table)
else:
flash('Error: Błąd bazy danych ')
else:
return redirect(url_for('main'))
@app.route("/edycja/dodaj",methods=['GET', 'POST'])
def dodaj_kwiatka():
global change_class
form = addflower.ReusableForm(request.form)
print(form.errors)
if request.method == 'POST':
flower=request.form['flower']
device=request.form['device']
pin=request.form['pin']
hh=request.form['hh']
mm=request.form['mm']
nexty=request.form['nexty']
if form.validate():
if(addflower.checkFlowerName(flower)==0):
if(addflower.checkFlowerPin(pin,device)==0):
if(addflower.checkFlowerHours(hh,mm)==0):
if(addflower.flower_add(session['id_u'],flower,device,pin,hh,mm,nexty)>0):
print(flower, device, pin, hh,mm,nexty)
change_class=1
return redirect(url_for('edycja'))
else:
flash('Error: Błąd bazy danych ')
elif(addflower.checkFlowerHours(hh,mm)<0):
flash('Error: Błąd bazy danych ')
else:
flash('Error: Podana godzina już zajęta przez inny kwiatek')
elif(addflower.checkFlowerPin(device,pin)<0):
flash('Error: Błąd bazy danych ')
else:
flash('Error: Pin zajęty przez inny kwiatek')
elif(addflower.checkFlowerName(flower)<0):
flash('Error: Błąd bazy danych ')
else:
flash('Error: Kwiatek o takiej nazwie już istnieje ')
else:
flash('Error: Wszystkie pola muszą być wypełnione ')
return render_template('addflower.html', form=form)
@app.route("/nawadnianie",methods=['GET', 'POST'])
def nawadnianie():
if(session.get('logged_in')==True):
table=tf.returnTable2(session['id_u'])
lista=request.form.getlist('selectThis[]')
if(ir.nawadnianie(table,lista)==2 and lista!=[]):
flash('Success: Dodano listę dodatkowego nawadniania')
elif(ir.nawadnianie(table,lista)==0 and lista!=[]):
flash('Error: Błąd bazy danych ')
return render_template('addwather.html',table=table)
else:
return redirect(url_for('main'))
@app.route("/historia",methods=['GET', 'POST'])
def historia():
if(session.get('logged_in')==True):
months=his.returnMonth()
years=his.returnYear()
flower=request.form.get('flower')
mm=request.form.get('MM')
yy=request.form.get('YYYY')
if((flower==None and mm==None and yy==None) or (flower=='' and mm=='0' and yy=='0')) :
print(flower,yy,mm)
currentMonth = datetime.now().month
currentYear = datetime.now().year
table=his.returnTable(currentMonth,currentYear)
return render_template('history.html',months=months,years=years,Year=currentYear,Month=currentMonth,table=table)
elif(flower=='' and mm!='0' and yy!='0'):
table=his.returnTable(mm,yy)
return render_template('history.html',months=months,years=years,Year=yy,Month=mm,table=table)
elif(flower!='' and mm!='0' and yy!='0'):
table=his.returnTable2(flower,mm,yy)
return render_template('history.html',months=months,years=years,Year=yy,Month=mm,table=table)
elif(flower!='' and mm=='0' and yy=='0'):
currentMonth = datetime.now().month
currentYear = datetime.now().year
table=his.returnTable2(flower,currentMonth,currentYear)
return render_template('history.html',months=months,years=years,Year=currentYear,Month=currentMonth,table=table)
else:
flash('Error: Błądy wykonywania ')
else:
return redirect(url_for('main'))
@app.route("/SignUp",methods=['GET', 'POST'])
def rejestracja():
form = sign_up.ReusableForm(request.form)
print(form.errors)
if request.method == 'POST':
name=request.form['name']
password=request.form['password']
hash_passwd=generate_password_hash(password)
email=request.form['email']
repeatpassword=request.form['repeatpassword']
if form.validate():
if(check_password_hash(hash_passwd, repeatpassword)):
if(sign_up.checkUser(name)<0):
if(sign_up.singing(name,email,hash_passwd)<=0):
flash('Error: Błąd bazy danych')
else:
return redirect(url_for('main'))
elif(sign_up.checkUser(name)==0):
flash('Error: Błąd bazy danych')
else:
flash('Error: Podany użytkownik już istnieje')
else:
flash('Error: Podane hasła się różnią')
else:
flash('Error: Wszystkie pola muszą być wypełnione ')
return render_template('SignUp.html', form=form)
@app.route('/logout')
def logout():
session.pop('logged_in',None)
flash('zostałeś wylogowany')
return redirect(url_for('menu'))
if __name__ == "__main__":
thread.start()
app.secret_key = 'ssssshhhhh'
app.run(port=port, debug=False)
<file_sep>import mysql.connector
from datetime import date, datetime, timedelta
def connecting():
cnx = mysql.connector.connect(user='phpmyadmin', password='****',
host='127.0.0.1',
database='phpmyadmin')
return cnx
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
from werkzeug import generate_password_hash, check_password_hash
import python.database_static as database_static
import mysql.connector
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
password = TextField('Password:', validators=[validators.required(), validators.Length(min=3, max=35)])
def login(name,password):
try:
hashed_passwd=None
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT Nazwa_User, mail, haslo, data_utw FROM `Users` WHERE Nazwa_User = '"+str(name)+"'"
result=cursor.execute(query)
print(result)
for (Nazwa_User, mail, haslo, data_utw) in cursor:
hashed_passwd=<PASSWORD>
print("{}, {}, {} was hired on {:%d %b %Y}".format(Nazwa_User, mail, haslo, data_utw))
count = cursor.rowcount
cursor.close()
cnx.close()
if(count>=0):
if(check_password_hash(hashed_passwd, password)):
count=2
else:
count=1
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def setId(name,password):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT id FROM `Users` WHERE Nazwa_User = '"+str(name)+"'"
result=cursor.execute(query)
print(result)
count=0
for id_u, in cursor:
count=int(id_u)
cursor.close()
cnx.close()
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
import python.database_static as database_static
import mysql.connector
class ReusableForm(Form):
flower = TextField('Flower:', validators=[validators.required()])
device = TextField('Device:', validators=[validators.required()])
pin = TextField('MySelect:', validators=[validators.required()])
hh = TextField('HH:', validators=[validators.required()])
mm = TextField('MM:', validators=[validators.required()])
nexty = TextField('Nexty:', validators=[validators.required()])
def checkedDevice(device):
if(device==1):
return "RP Zero";
elif(device==2):
return "EXP0";
elif(device==3):
return "EXP1";
elif(device==4):
return "EXP2";
else:
return "nothing";
def flower_add(id_u,name,device,pin,hh,mm,nexty):
try:
if(int(device)>0):
cnx = database_static.connecting()
cursor = cnx.cursor()
today = datetime.now().date()
tomorrow=datetime.now().date()+timedelta(days=1)
db=datetime.strptime(str(tomorrow)+" "+str(hh)+":"+str(mm),'%Y-%m-%d %H:%M')
db2=datetime.strptime(str(hh)+":"+str(mm),'%H:%M').time()
dev2=checkedDevice(int(device))
add_user = ("INSERT INTO Flowers "
"(id_u, Nazwa, Zlacze, Pin, data_utw, Godzina_podl, data_podlewania, okr_podl) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)")
data_employee = (str(id_u), name,dev2,str(pin) ,today, db2, db, str(nexty))
result=cursor.execute(add_user, data_employee)
print(result)
cnx.commit()
cursor.close()
cnx.close()
return 2
else:
return 0
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def checkFlowerName(name):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT Nazwa FROM `Flowers` WHERE Nazwa = '"+str(name)+"'"
result=cursor.execute(query)
for (name) in cursor:
print("{}".format(name))
count = cursor.rowcount
count+=1
cursor.close()
cnx.close()
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return -1
def checkFlowerPin(pin,zlacze):
try:
print(zlacze)
cnx = database_static.connecting()
cursor = cnx.cursor()
dev2=checkedDevice(int(zlacze))
query="SELECT Nazwa, Zlacze, Pin FROM `Flowers` WHERE Zlacze = '"+dev2+"'"+ " AND Pin='"+str(pin)+"'"
print(query)
result=cursor.execute(query)
for (Nazwa, Zlacze, Pin) in cursor:
print("{}, {}, {}".format(Nazwa, Zlacze, Pin))
count = cursor.rowcount
count+=1
cursor.close()
cnx.close()
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def checkFlowerHours(hh,mm):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
db=datetime.strptime(str(hh)+":"+str(mm),"%H:%M").time()
query="SELECT Nazwa,Godzina_podl,data_podlewania FROM `Flowers` WHERE Godzina_podl = '"+str(db)+"'"
result=cursor.execute(query)
print(result)
for (Nazwa, Zlacze, Pin) in cursor:
print("{}, {}, {}".format(Nazwa, Zlacze, Pin))
count = cursor.rowcount
count+=1
cursor.close()
cnx.close()
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
from werkzeug import generate_password_hash, check_password_hash
import python.database_static as database_static
import mysql.connector
def delete_flower(listaFlowers,lista):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="DELETE FROM `Flowers` WHERE "
print(query)
for i in range(len(listaFlowers)):
query2=[]
for j in range(len(lista)):
if(i==int(lista[j])):
print("usunieto ")
print(listaFlowers[i])
query2="Nazwa='" +listaFlowers[i][0]
query2+="' AND ZLACZE='" +listaFlowers[i][1]
query2+="' AND Pin='"+str(listaFlowers[i][2])
query2+="' AND data_utw='"+str(listaFlowers[i][3])
query2+="' AND Godzina_podl='"+str(listaFlowers[i][4])
query2+="' AND data_podlewania='"+str(listaFlowers[i][5])
query2+="' AND okr_podl='"+str(listaFlowers[i][6])+"'"
s=str(query)+str(query2)
cursor.execute(s)
print(s)
cnx.commit()
cursor.close()
cnx.close()
return 2
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
import python.database_static as database_static
import mysql.connector
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
email = TextField('Email:', validators=[validators.required(), validators.Length(min=6, max=35)])
password = TextField('Password:', validators=[validators.required(), validators.Length(min=3, max=35)])
repeatpassword = TextField('Repeat Password:', validators=[validators.required(), validators.Length(min=3, max=35)])
def singing(name,email,password):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
tomorrow = datetime.now().date()
add_user = ("INSERT INTO Users "
"(Nazwa_User, mail, haslo, data_utw) "
"VALUES (%s, %s, %s, %s)")
data_employee = (name, email, password ,tomorrow)
cursor.execute(add_user, data_employee)
cnx.commit()
cursor.close()
cnx.close()
return 2
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def checkUser(name):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT Nazwa_User, mail, haslo, data_utw FROM `Users` WHERE Nazwa_User = '"+str(name)+"'"
result=cursor.execute(query)
print(result)
for (Nazwa_User, mail, haslo, data_utw) in cursor:
print("{}, {}, {} was hired on {:%d %b %Y}".format(Nazwa_User, mail, haslo, data_utw))
count = cursor.rowcount
cursor.close()
cnx.close()
return count
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
<file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from datetime import date, datetime, timedelta
from werkzeug import generate_password_hash, check_password_hash
import python.database_static as database_static
import mysql.connector
def returnMonth():
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT DISTINCT MONTH(data_podlewania) FROM `History`"
r=cursor.execute(query)
months=[]
for month, in cursor:
months.append(month)
cursor.close()
cnx.close()
return months
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def returnYear():
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT DISTINCT Year(data_podlewania) FROM `History`"
r=cursor.execute(query)
years=[]
for year, in cursor:
years.append(year)
cursor.close()
cnx.close()
return years
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def returnTable(curMonth,curYear):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT f.nazwa,h.data_podlewania,h.data_nast_podl from `History` h JOIN `Flowers` f ON h.id_f=f.id_f WHERE MONTH(h.data_podlewania)="+str(curMonth)+" AND YEAR(h.data_podlewania)="+str(curYear)
r=cursor.execute(query)
result=cursor.fetchall()
count = cursor.rowcount
cursor.close()
cnx.close()
return result
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
def returnTable2(flower,curMonth,curYear):
try:
cnx = database_static.connecting()
cursor = cnx.cursor()
query="SELECT f.nazwa,h.data_podlewania,h.data_nast_podl from `History` h JOIN `Flowers` f ON h.id_f=f.id_f WHERE MONTH(h.data_podlewania)="+str(curMonth)+" AND YEAR(h.data_podlewania)="+str(curYear)+" AND f.nazwa='"+str(flower)+"'"
r=cursor.execute(query)
result=cursor.fetchall()
count = cursor.rowcount
cursor.close()
cnx.close()
return result
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
return 0
| bbf965940b657d7b0ee52d7ee5d5b33b6a4e7070 | [
"JavaScript",
"Python"
] | 11 | Python | piotrtr92/sys_nawadniania_2 | 57f2072190c7fffea8a351108b15d561efa24a64 | 02ba69a78500fbc9976d2da9c2ef94b13ab3f348 |
refs/heads/master | <file_sep>const HLRU = require('hashlru');
const hash = require('object-hash');
const latency = require('./latency');
class Cache {
/**
* @param {number} size
*/
constructor(size) {
this.enabled = !!size;
// if enabled - use it
if (this.enabled) {
// @ts-expect-error invalid lib definition
this.cache = HLRU(size);
}
}
/**
*
* @param {any} message
* @param {number} maxAge
* @returns
*/
get(message, maxAge) {
if (this.enabled === false) {
process.emitWarning('tried to use disabled cache', {
code: 'MF_AMQP_CACHE_0001',
detail: 'enable cache to be able to use it',
});
return null;
}
if (typeof maxAge !== 'number' && maxAge > 0) {
process.emitWarning('maxAge must be ', {
code: 'MF_AMQP_CACHE_0002',
detail: 'ensure maxAge is set to a positive number',
});
return null;
}
const hashKey = hash(message);
const response = this.cache.get(hashKey);
if (response !== undefined) {
if (latency(response.maxAge) < maxAge) {
return response;
}
this.cache.remove(hashKey);
}
return hashKey;
}
/**
*
* @param {string} key
* @param {any} data
* @returns
*/
set(key, data) {
if (this.enabled === false) {
process.emitWarning('tried to use disabled cache', {
code: 'MF_AMQP_CACHE_0001',
detail: 'enable cache to be able to use it',
});
return null;
}
// only use string keys
if (typeof key !== 'string') {
process.emitWarning('key isnt string', {
code: 'MF_AMQP_CACHE_0003',
});
return null;
}
return this.cache.set(key, { maxAge: process.hrtime(), value: data });
}
}
module.exports = Cache;
<file_sep>const initTracer = require('jaeger-client').initTracer;
const AMQPTransport = require('../src');
const Promise = require('bluebird');
const reporter = {
flushIntervalMs: 300,
logSpans: false,
};
const sampler = {
type: 'const',
param: 1,
};
const opts = {
logger: require('../lib/loggers/bunyan-logger'),
};
const connection = {
host: process.env.RABBITMQ_PORT_5672_TCP_ADDR || 'localhost',
port: process.env.RABBITMQ_PORT_5672_TCP_PORT || 5672,
};
const server = {
connection: Object.assign({}, connection),
name: 'server',
queue: 'consumer',
listen: ['tracing-key', 'pomegranate.*'],
tracer: initTracer({ serviceName: 'rpc-server', reporter, sampler }, opts),
};
const client = {
connection: Object.assign({}, connection),
name: 'client',
private: true,
tracer: initTracer({ serviceName: 'rpc-client', reporter, sampler }, opts),
};
const echo = (message, properties, actions, next) => {
if (!message) return next(new Error('invalid message'));
if (message.err) return next(message.err);
return next(null, message);
};
Promise.join(
AMQPTransport.connect(server, echo),
AMQPTransport.connect(client)
)
.spread((rpcServer, rpcClient) => Promise.all([
rpcClient.publishAndWait('tracing-key', {}).reflect(),
rpcClient.publishAndWait('pomegranate.turnKey', {}).reflect(),
rpcClient.publishAndWait('pomegranate.turnKey').reflect(),
]));
<file_sep>const assert = require('assert');
describe('utils: latency', () => {
const latency = require('../src/utils/latency');
it('displays latency in miliseconds', () => {
const time = latency(process.hrtime());
assert.ok(time < 0.1, `process.hrtime(process.hrtime()) takes more than 10 microseconds: ${time}`);
});
it('converts to miliseconds correctly with roundup to 3d digit', () => {
// seconds
// nanoseconds
assert.equal(latency.toMiliseconds([1, 1001000]), 1001.001);
});
});
<file_sep>const AMQPTransport = require('../src');
const configuration = {
exchange: 'test-exchange-not-durable',
queue: 'vasya',
listen: ['vasya.*'],
exchangeArgs: {
autoDelete: true,
},
connection: {
host: process.env.RABBITMQ_PORT_5672_TCP_ADDR || 'localhost',
port: process.env.RABBITMQ_PORT_5672_TCP_PORT || 5672,
},
};
AMQPTransport.connect(configuration);
<file_sep>module.exports = {
node: "16",
auto_compose: true,
services: ['rabbitmq'],
nycCoverage: false,
nycReport: false,
test_framework: 'c8 /src/node_modules/.bin/mocha',
extras: {
tester: {
environment: {
NODE_ENV: 'test',
RABBITMQ_PORT_5672_TCP_ADDR: 'rabbitmq'
}
}
},
tests: "./test/*.js",
rebuild: ["microtime"],
pre: "rimraf ./coverage/tmp || true",
post_exec: "pnpm exec -- c8 report -r text -r lcov"
}
<file_sep>/**
* @param {[number, number]} hrtime
* @returns
*/
function toMiliseconds(hrtime) {
return (hrtime[0] * 1e3) + (Math.round(hrtime[1] / 1e3) / 1e3);
}
/**
* @param {[number, number]} time
* @returns
*/
module.exports = function latency(time) {
return toMiliseconds(process.hrtime(time));
};
module.exports.toMiliseconds = toMiliseconds;
<file_sep># RabbitMQ / AMQP Node.js Transport for Microservices
<img alt="Microfleet AMQP" src="https://raw.githubusercontent.com/microfleet/transport-amqp/master/assets/mf-concept-amqp.png" width="412" height="208" />
Contains RabbitMQ-based transport for establishing a net of loosely coupled microservices with a simple RPC-style calling interface using Node.js
[](https://badge.fury.io/js/%40microfleet%2Ftransport-amqp)
[](https://semaphoreci.com/makeomatic/transport-amqp)
[](https://github.com/semantic-release/semantic-release)
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fmicrofleet%2Ftransport-amqp?ref=badge_shield)
## Install
`npm i @microfleet/transport-amqp -S`
`yarn add @microfleet/transport-amqp`
Heavily relies on `dropbox/amqp-coffee` & `@microfleet/amqp-coffee` lib for establishing communication with RabbitMQ using AMQP protocol
## Usage
Using AMQP is often not as easy as it sounds - managing connection to your cluster, lifecycle of the queues, bindings & exchanges, as well guaranteed delivery of messages - that all can be a burden. This module has been used in production for over 5 years now and had many iterations to fine-tune reconnection strategies and message delivery issues
Essentially it gives you an opinionated subset of AMQP spec to create guaranteed completion worker queues or an RPC service.
### Configuration
Please consult with [configuration schemas](src/schema.js) where every possible setting is annotated and described
### Establish connection
There are several strategies that are supported with this module out-of-the-box:
* 1 consumption queue for all routes (internally - 1 channel that consumes a queue bound to all routing keys)
* 1 RPC queue (internally uses 1 channel for publishing and 1 channel for consumption of responses)
* 1 consumption queue per each route
And mix of each of these strategies.
#### Long-running microservice
##### Message handling
Each message that is delivered through AMQP to consumer will be received using the following routing function.
Messages must be encoded in JSON, which is transparently handled by this library and follow idiomatic { err, message } structure for Node.js
```js
const router = (message, properties, actions, next) => {
// message - anything that was sent to the consumer
// if sent using this library - you can send any type of data supported by Node.js
// except for streams
// properties - this is basic message content
// more info can be found here - https://www.rabbitmq.com/amqp-0-9-1-reference.html#class.basic
// those of value are:
// `properties.headers`, `properties.correlationId`, `properties.replyTo`
// actions - if `neck` (prefetchCount >= 0, noAck: false) is defined, it would have
// - .ack()
// - .reject()
// - .retry()
// next - standard callback with (err, response), if no `replyTo` is set response will only be logged into
// console. This would be the case when someone published a message and they don't care about the response
// typically that would happen when the task is considered long-running and we can't reliably respond fast
// enough for the publisher
};
```
##### One permanent queue - many bound routes
```js
const AMQPTransport = require('@microfleet/transport-amqp');
const options = {
// will create queue with the following name:
queue: 'permanent-queue-name',
// will bind that queue on the exchange
listen: ['routing.key', 'prefix.#', '*.log'],
// will create exchange with that name
exchange: 'node-services',
};
AMQPTransport.connect(options, router).then((amqp) => {
// at this point we've connected
// created a consumed queue and router is called when messages are delivered to it
// amqp is a connected instance of an AMQPTransport
});
```
##### Permanent queue per bound route
```js
const AMQPTransport = require('@microfleet/transport-amqp');
const options = {
// will create queue with the following name:
queue: 'permanent-queue-name',
// will bind that queue on the exchange
listen: ['routing.key', 'prefix.#', '*.log'],
// will create exchange with that name
exchange: 'node-services',
};
// this is an Array of queue options for each queue
// you can overwrite queue names here
const queueOpts = [{
// extra settings for queue `permanent-queue-name-routing.key`
arguments: {
'x-dead-letter-exchange': 'something'
}
}, {
// overwrite name of the queue for the second route
queue: 'awesome-queue',
}];
AMQPTransport.multiConnect(options, router, queueOpts).then((amqp) => {
// at this point we've connected
// created several consumed queues with names:
// * `permanent-queue-name-routing.key` bound to `routing.key`
// * `awesome-queue` bound to `prefix.#`
// * `permanent-queue-name-..log` bound to `*.log`
// amqp is a connected instance of an AMQPTransport
});
```
#### RPC client
Once you have a long-running microservice handling messages - you can interact with it using same adapter
```js
const AMQPTransport = require('@microfleet/transport-amqp');
const opts = { private: true }; // establish private queue right after connecting
// no router passed - means we are not creating consumed queue right away
// we may still do it later, but for now it's only good to do RPC calls
AMQPTransport.connect(opts).then((amqp) => {
// we've connected to RabbitMQ server and are ready to send messages
// send messages using routing keys:
// return Promise, which resolves
// based on publishOptions
// * confirm - waits for commit from AMQP server before resolving
// * immediate - waits for the message to be delivered, if it can't be - rejects
// * other options - read more in the schema.js file linked earlier
amqp.publish(routingKey, message, publishOptions, [parentSpan])
.then(() => {
// sent
})
.catch((err) => {
// failed to send
})
// same as publish, but sets correlation-id and reply-to properties
// on the message, allowing consumer to response
// resolves with
amqp.publishAndWait(routingKey, message, publishOptions, [parentSpan])
.then((response) => {
// do whatever you want
})
.catch((err) => {
// either failed to send or response contained an error - work with it here
})
// Other option is to work not with the routing keys, but with queues directly
// for that there are 2 similar methods
// apart from `routingKey` and `queueName` - everything else works the same way
amqp.send(queueName, message, publishOptions, [parentSpan])
amqp.sendAndWait(queueName, message, publishOptions, [parentSpan])
});
```
#### Graceful shutdown
If the graceful shutdown of your service is needed, to stop receiving incoming messages but continue processing, call `closeAllConsumers()`.
This method closes all consumers but leaves the transport connection active. You can process all incoming messages and securely close connections.
```js
AMQPTransport.connect(options, router).then((amqp) => {
service.on('close', async () => {
await amqp.closeAllConsumers();
// do everything you need
// ..
await amqp.close();
})
});
```
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fmicrofleet%2Ftransport-amqp?ref=badge_large)
<file_sep># Consumer Stop support
## Overview and motivation
Currently `amqp-transport` module does not export methods allowing to close consumers independently of transport.
Transport uses WeakMap's for storing consumers and queue references with keys eq `local function` which are not available from outside.
When you need to stop receiving incoming messages and leave connection to rabbitmq alive, you must implement
a wrapper that allows you to save consumer references to be able to cancel consumption on demand.
## Public property `consumers`
Instead of having a WeakMap for established consumers and reconnection handlers we
start retaining them. This allows us to iterate on all the stored consumers and close them
for consuming in an easy fashion. Rest remains the same. One must be careful to cleanup when
they are done with the consumers or a leak might occur
## Public closeAllConsumers() method
Iterates over `consumers` property and calls `stopConsumedQueue` method. Returns Promise with multiple `stopConsumedQueue` Promises.
```js
const transport = AMQPTransport.connect();
// stop only consumers
await transport.closeConsumers();
```
<file_sep>const is = require('is');
const Errors = require('common-errors');
// generate internal error class for passing between amqp
/**
* @class MSError
* @param {string} message
*/
const MSError = Errors.helpers.generateClass('MSError', {
globalize: false,
args: ['message'],
});
/**
* Serializes Own Properties of Error
* @this {Record<string, any>}
* @param {string} key
* @returns {{ key: string, value: any }}
*/
function serializeOwnProperties(key) {
return {
key,
value: this[key],
};
}
/**
* Cached Deserialized Own Properties
* @this {Record<string, any>}
* @param {{ key: string, value: any }} data
* @returns {void}
*/
function deserializeOwnProperties(data) {
this[data.key] = data.value;
}
/**
* Make sure we can transfer errors via rabbitmq through toJSON() call
* @param {Error} error
* @return {{ type: 'ms-error', data: Record<string, any> }}
*/
function serializeError(error) {
// serialized output
return {
type: 'ms-error',
data: Object
.getOwnPropertyNames(error)
.filter((prop) => typeof error[prop] !== 'function')
.map(serializeOwnProperties, error),
};
}
/**
* Make sure we get a valid JS error
* @param {Object} error
* @return {ReturnType<MSError>}
*/
function deserializeError(error) {
const deserialized = new MSError();
error.forEach(deserializeOwnProperties, deserialized);
return deserialized;
}
/**
* @param {string} key
* @param {any} value
*/
function jsonSerializer(key, value) {
if (value instanceof Error) {
return serializeError(value);
}
if (value && value.error instanceof Error) {
value.error = serializeError(value.error);
}
if (value instanceof Map) {
return { type: 'map', data: Object.fromEntries(value) };
}
if (value instanceof Set) {
return { type: 'set', data: Array.from(value) };
}
return value;
}
function jsonDeserializer(key, value) {
if (!is.object(value)) {
return value;
}
const { data } = value;
if (!data) {
return value;
}
const { type } = value;
switch (type) {
case 'ms-error':
return deserializeError(data);
case 'Buffer':
case 'buffer':
return Buffer.from(data);
case 'ms-set':
return new Set(data);
case 'ms-map':
return new Map(Object.entries(data));
default:
return value;
}
}
exports.jsonSerializer = jsonSerializer;
exports.jsonDeserializer = jsonDeserializer;
exports.MSError = MSError;
<file_sep>/**
* @typedef { import("opentracing").Span } Span
* @typedef { import("opentracing").Tracer } Tracer
*
* @typedef AMQPMessage
* @property {Object} properties - amqp properties
* @property {Record<string, any>} properties.headers - amqp headers
* @property {string} [properties.appId] sender diagnostics data
* @property {string} [properties.routingKey] amqp routing-key
* @property {string} [properties.replyTo] amqp reply-to field
* @property {string} [properties.correlationId] amqp correlation-id
* @property {string} [properties.contentType] amqp message content-type
* @property {string} [properties.contentEncoding] amqp message content-encoding
* @property {() => void} [ack] - Acknowledge if nack is `true`.
* @property {() => void} [reject] - Reject if nack is `true`.
* @property {() => void} [retry] - Retry msg if nack is `true`.
* @property {opentracing.Span} [span] - optional span
*
* @typedef ConsumerBase
* @property {(err: any, result?: any) => void} cancel
* @property {() => void} close
* @property {string} consumerTag
*
* @typedef {EventEmitter & ConsumerBase} Consumer
*
* @typedef PublishOptions
* @property {string} [contentType] - message content-type
* @property {string} [contentEncoding] - message encoding, defaults to `plain`
* @property {string} [exchange] - exchange to publish to
* @property {string} [correlationId] - used to match messages when getting a reply
* @property {string} [exchange] - will be overwritten by exchange thats passed
* @property {boolean} [gzip] - whether to encode using gzip
* @property {boolean} [skipSerialize] - whether it was already serialized earlier
* @property {boolean} [confirm] - require ack from server on publish
* @property {boolean} [mandatory] - require queue to exist on publish
* @property {boolean} [immediate] - require message to be immediately routedd
* @property {1|2} [deliveryMode] - transient or persistant, default to 1
* @property {number} [timeout] - optional ttl value for message in the publish/send methods
* https://github.com/dropbox/amqp-coffee/blob/6d99cf4c9e312c9e5856897ab33458afbdd214e5/src/lib/Publisher.coffee#L90
*
* @property {Record<string, string | number | boolean>} [headers]
*
* @typedef QueueBindOptions
* @property {boolean} [autoDelete]
* @property {Record<string, string>} [arguments]
*
* @typedef Queue
* @property {Object} queueOptions
* @property {string} queueOptions.queue
* @property {string[]} [_routes]
* @property {(exchange: string, routingKey: string, options: QueueBindOptions) => Promise<any>} bindAsync
*
* @typedef AMQPError
* @property {string} replyText
*/
// deps
const Bluebird = require('bluebird');
const gunzip = Bluebird.promisify(require('zlib').gunzip);
const gzip = Bluebird.promisify(require('zlib').gzip);
const uuid = require('uuid');
const flatstr = require('flatstr');
const stringify = require('json-stringify-safe');
const EventEmitter = require('eventemitter3');
const { once } = require('events');
const os = require('os');
const is = require('is');
const assert = require('assert');
const opentracing = require('opentracing');
const {
ConnectionError,
NotPermittedError,
ValidationError,
InvalidOperationError,
ArgumentError,
HttpStatusError,
} = require('common-errors');
// lodash fp
const merge = require('lodash/merge');
const defaults = require('lodash/defaults');
const noop = require('lodash/noop');
const uniq = require('lodash/uniq');
const pick = require('lodash/pick');
const readPkg = require('read-pkg');
// local deps
const { Joi, schema } = require('./schema');
const AMQP = require('./utils/transport');
const ReplyStorage = require('./utils/reply-storage');
const Backoff = require('./utils/recovery');
const Cache = require('./utils/cache');
const latency = require('./utils/latency');
const loggerUtils = require('./loggers');
const generateErrorMessage = require('./utils/error');
const helpers = require('./helpers');
const { kReplyHeaders } = require('./constants');
// serialization functions
const { jsonSerializer, jsonDeserializer } = require('./utils/serialization');
// cache references
const { AmqpDLXError } = generateErrorMessage;
const { wrapError, setQoS } = helpers;
const { Tags, FORMAT_TEXT_MAP } = opentracing;
const PARSE_ERR = new ValidationError('couldn\'t deserialize input', '500', 'message.raw');
const pkg = readPkg.sync();
/**
* Wraps regular in a bluebird promise
* @template T
* @param {Span} span opentracing span
* @param {PromiseLike<T>} promise pending promise
* @return {Bluebird<T>}
*/
const wrapPromise = (span, promise) => Bluebird.resolve((async () => {
try {
return await promise;
} catch (error) {
span.setTag(Tags.ERROR, true);
span.log({
event: 'error',
'error.object': error,
message: error.message,
stack: error.stack,
});
throw error;
} finally {
span.finish();
}
})());
/**
*
* @param {any} message
* @param {PublishOptions} publishOptions
* @returns
*/
const serialize = async (message, publishOptions) => {
let serialized;
switch (publishOptions.contentType) {
case 'application/json':
case 'string/utf8':
serialized = Buffer.from(flatstr(stringify(message, jsonSerializer)));
break;
default:
throw new Error('invalid content-type');
}
if (publishOptions.contentEncoding === 'gzip') {
return gzip(serialized);
}
return serialized;
};
/**
* @param {any} data
* @param {import("pino").BaseLogger} log
* @returns
*/
function safeJSONParse(data, log) {
try {
return JSON.parse(data, jsonDeserializer);
} catch (err) {
log.warn({ err, data: String(data) }, 'Error parsing buffer');
return { err: PARSE_ERR };
}
}
/**
* @template {string} T
* @param {T | T[]} routes
* @returns {T[]}
*/
const toUniqueStringArray = (routes) => (
Array.isArray(routes) ? uniq(routes) : [routes]
);
/**
* Routing function HOC with reply RPC enhancer
* @param {Function} messageHandler
* @param {AMQPTransport} transport
* @returns {(message: any, properties: AMQPMessage['properties'], raw: AMQPMessage) => any}
*/
const initRoutingFn = (messageHandler, transport) => {
/**
* Response Handler Function. Sends Reply or Noop log.
* @param {AMQPMessage} raw - Raw AMQP Message Structure
* @param {Error | null} error - Error if it happened.
* @param {any} data - Response data.
* @returns {Promise<any>}
*/
async function responseHandler(raw, error, data) {
const { properties, span } = raw;
return !properties.replyTo || !properties.correlationId
? transport.noop(error, data, span, raw)
: transport.reply(properties, { error, data }, span, raw);
}
/**
* Initiates consumer message handler.
* @param {any} message - Data passed from the publisher.
* @param {AMQPMessage['properties']} properties - AMQP Message properties.
* @param {AMQPMessage} raw - Original AMQP message.
* @returns {any}
*/
return function router(message, properties, raw) {
// add instrumentation
const appId = safeJSONParse(properties.appId, this.log);
// opentracing instrumentation
const childOf = this.tracer.extract(FORMAT_TEXT_MAP, properties.headers || {});
const span = this.tracer.startSpan(`onConsume:${properties.routingKey}`, {
childOf,
});
span.addTags({
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_SERVER,
[Tags.PEER_SERVICE]: appId.name,
[Tags.PEER_HOSTNAME]: appId.host,
});
// define span in the original message
// so that userland has access to it
raw.span = span;
return messageHandler(message, properties, raw, responseHandler.bind(undefined, raw));
};
};
/**
* @template [T=any]
* @param {Object} response
* @oaram {T} response.data
* @oaram {Record<string, any>} response.headers
* @param {Object} replyOptions
* @param {boolean} replyOptions.simpleResponse
* @returns {T | { data: T, headers: Record<string, any>}}
*/
function adaptResponse(response, replyOptions) {
return replyOptions.simpleResponse === false ? response : response.data;
}
/**
* @template [T=any]
* @param {Object} message
* @param {T} message.data
* @param {Error | null} message.error
* @param {AMQPMessage['properties']} properties
* @returns {{ data: T, headers: AMQPMessage['properties']['headers'] }}
*/
function buildResponse(message, properties) {
const { headers } = properties;
const { data } = message;
return {
headers,
data,
};
}
const extendMessageProperties = [
'deliveryTag',
'redelivered',
'exchange',
'routingKey',
'weight',
];
const error406 = { replyCode: 406 };
/**
* @class AMQPTransport
*/
class AMQPTransport extends EventEmitter {
/**
* Instantiate AMQP Transport
* @param {Object} opts, defaults to {}
*/
constructor(opts = {}) {
super();
// prepare configuration
const config = this.config = Joi.attempt(opts, schema, {
allowUnknown: true,
});
this.config = config;
// prepares logger
this.log = loggerUtils.prepareLogger(config);
this.log.debug({ config }, 'used configuration');
// init cache or pass-through operations
this.cache = new Cache(config.cache);
/**
* @readonly
* reply storage, where we'd save correlation ids
* and callbacks to be called once we are done
*/
this.replyStorage = new ReplyStorage();
/**
* delay settings for reconnect
* @readonly
*/
this.recovery = new Backoff(config.recovery);
/**
* @readonly
* @type Tracer
*/
this.tracer = config.tracer || new opentracing.Tracer();
/**
* @private
*/
this._replyTo = null;
/**
* @private
*/
this._consumers = new Map();
/**
* @private
*/
this._queues = new WeakMap();
/**
* @private
*/
this._reconnectionHandlers = new WeakMap();
/**
* @private
*/
this._boundEmit = this.emit.bind(this);
/**
* @private
*/
this._onConsume = this._onConsume.bind(this);
/**
* @private
*/
this._on406 = this._on406.bind(this);
/**
* @private
*/
this._onClose = this._onClose.bind(this);
/**
* @private
*/
this._onConnect = this._onConnect.bind(this);
// Form app id string for debugging
/**
* @private
*/
this._appID = {
name: this.config.name,
host: os.hostname(),
pid: process.pid,
utils_version: pkg.version,
version: opts.version || 'n/a',
};
// Cached serialized value
/**
* @private
*/
this._appIDString = stringify(this._appID);
/**
* @private
*/
this._defaultOpts = { ...config.defaultOpts };
this._defaultOpts.appId = this._appIDString;
/**
* @private
*/
this._extraQueueOptions = {};
// DLX config
if (config.dlx.enabled === true) {
// there is a quirk - we must make sure that no routing key matches queue name
// to avoid useless redistributions of the message
this._extraQueueOptions.arguments = { 'x-dead-letter-exchange': config.dlx.params.exchange };
}
}
/**
* Connects to AMQP, if config.router is specified earlier,
* automatically invokes .consume function
* @return {Bluebird<AMQPTransport>}
*/
connect() {
const { _amqp: amqp, config } = this;
if (amqp) {
switch (amqp.state) {
case 'opening':
case 'open':
case 'reconnecting': {
const msg = 'connection was already initialized, close it first';
const err = new InvalidOperationError(msg);
return Bluebird.reject(err);
}
default:
// already closed, but make sure
amqp.close();
this._amqp = null;
}
}
return Bluebird
.fromNode((next) => {
this._amqp = new AMQP(config.connection, next);
this._amqp.on('ready', this._onConnect);
this._amqp.on('close', this._onClose);
})
.return(this);
}
/**
* Noop function with empty correlation id and reply to data
* @param {Error | null} error
* @param {any} data
* @param {Span} [span]
* @param {AMQPMessage} [raw]
*/
noop(error, data, span, raw) {
const msg = stringify({ error, data }, jsonSerializer);
this.log.debug('when replying to message with %s response could not be delivered', msg);
if (span !== undefined) {
if (error) {
span.setTag(Tags.ERROR, true);
span.log({
event: 'error', 'error.object': error, message: error.message, stack: error.stack,
});
}
span.finish();
}
if (raw !== undefined) {
this.emit('after', raw);
}
}
/**
* Stops consumers and closes transport
*/
async _close() {
const { _amqp: amqp } = this;
await this.closeAllConsumers();
try {
await new Bluebird((resolve, reject) => {
amqp.once('close', resolve);
amqp.once('error', reject);
amqp.close();
});
} finally {
this._amqp = null;
amqp.removeAllListeners();
}
}
close() {
const { _amqp: amqp } = this;
if (amqp) {
switch (amqp.state) {
case 'opening':
case 'open':
case 'reconnecting':
return this._close();
default:
this._amqp = null;
return Bluebird.resolve();
}
}
const err = new InvalidOperationError('connection was not initialized in the first place');
return Bluebird.reject(err);
}
/**
* Create queue with specified settings in current connection
* also emit new event on message in queue
*
* @param {Object} opts - queue parameters
*/
async createQueue(opts) {
const { _amqp: amqp, log, _onConsume } = this;
// prepare params
const ctx = Object.create(null);
const userParams = typeof opts === 'string' ? { queue: opts } : opts;
const requestedName = userParams.queue;
const params = merge({ autoDelete: !requestedName, durable: !!requestedName }, userParams);
log.debug({ params }, 'initializing queue');
const queue = ctx.queue = await amqp.queueAsync(params);
await Bluebird
.resolve(queue.declareAsync())
.catch(error406, this._on406.bind(this, params))
.tapCatch((err) => {
log.warn({ err, queue: params.queue }, 'failed to init queue');
});
// copy queue options
const options = ctx.options = { ...ctx.queue.queueOptions };
const queueName = options.queue;
log.info({ queue: queueName }, 'queue created');
if (!params.router) {
return ctx;
}
log.info({ queue: options.queue }, 'consumer is being created');
// setup consumer
const messageHandler = _onConsume(params.router);
ctx.consumer = await amqp.consumeAsync(queueName, setQoS(params), messageHandler);
return ctx;
}
handlePrivateConsumerError(consumer, queue, err) {
const { error } = err;
if (error && error.replyCode === 404 && error.replyText.indexOf(queue) !== -1) {
// https://github.com/dropbox/amqp-coffee#consumer-event-error
// handle consumer error on reconnect and close consumer
// warning: other queues (not private one) should be handled manually
this.log.error({ err: error }, 'consumer returned 404 error');
// reset replyTo queue and ignore all future errors
consumer.removeAllListeners('error');
consumer.removeAllListeners('cancel');
consumer.on('error', noop);
consumer.close();
// recreate queue
if (this._replyTo !== false) this.createPrivateQueue();
return;
}
this.log.error({ err }, 'private consumer returned err');
this.emit('error', err);
}
// access-refused 403
// The client attempted to work with a server entity
// to which it has no access due to security settings.
// not-found 404
// The client attempted to work with a server entity that does not exist.
// resource-locked 405
// The client attempted to work with a server entity
// to which it has no access because another client is working with it.
// precondition-failed 406
// The client requested a method that was not allowed
// because some precondition failed.
/**
*
* @param {Consumer} consumer
* @param {Queue} queue
* @param {any} err
* @param {any} res
* @returns
*/
async handleConsumerError(consumer, queue, err, res) {
const error = err.error || err;
// https://www.rabbitmq.com/amqp-0-9-1-reference.html -
switch (error.replyCode) {
// ignore errors
case 311:
case 313:
this.log.error({ err, res }, 'error working with a channel');
return null;
case 404:
if (error.replyText && error.replyText.includes(queue.queueOptions.queue)) {
return this.rebindConsumer(consumer, error, res);
}
return null;
default:
this.log.warn({ err }, 'unhandled consumer error');
return this.rebindConsumer(consumer, error, res);
}
}
/**
*
* @param {Consumer} consumer
* @param {AMQPError | null} err
* @param {any} res
* @returns
*/
async rebindConsumer(consumer, err, res) {
const msg = err ? err.replyText : 'uncertain';
// cleanup a bit
this.log.warn({ err, res }, 're-establishing connection after %s', msg);
// saved reference to re-establishing function
const establishConsumer = this._reconnectionHandlers.get(consumer);
if (establishConsumer == null) {
this.log.fatal({ err, res }, 'failed to fetch connection handler');
return;
}
try {
await this.closeConsumer(consumer);
await Bluebird.delay(this.recovery.get('consumed', 1));
} catch (e) {
this.log.error({ err: e }, 'failed to close consumer');
} finally {
await establishConsumer();
}
}
/**
* @param {Consumer} consumer
*/
handlePrivateConsumerCancel(consumer) {
consumer.removeAllListeners('error');
consumer.removeAllListeners('cancel');
consumer.on('error', noop);
consumer.close();
// recreate queue unless it is already being recreated
if (this._replyTo !== false) {
this.createPrivateQueue();
}
}
/**
* Create unnamed private queue (used for reply events)
* @param {number} [attempt]
*/
async createPrivateQueue(attempt = 0) {
const replyTo = this._replyTo;
const queueOpts = {
...this.config.privateQueueOpts,
router: this._privateMessageRouter, // private router here
queue: replyTo || `microfleet.${uuid.v4()}`, // reuse same private queue name if it was specified before
};
// reset current state
this._replyTo = false;
let createdQueue;
try {
const { consumer, queue, options } = createdQueue = await this.createQueue(queueOpts);
// remove existing listeners
consumer.removeAllListeners('error');
consumer.removeAllListeners('cancel');
// consume errors - re-create when we encounter 404 or on cancel
consumer.on('error', this.handlePrivateConsumerError.bind(this, consumer, options.queue));
consumer.once('cancel', this.handlePrivateConsumerCancel.bind(this, consumer));
// declare _replyTo queueName
this._replyTo = options.queue;
// bind temporary queue to headers exchange for DLX messages
// NOTE: if this fails we might have a problem where expired messages
// are not delivered & private queue is never ready
const dlxConfig = this.config.dlx;
if (dlxConfig.enabled === true) {
await this.bindHeadersExchange(queue, this._replyTo, dlxConfig.params, 'reply-to');
}
} catch (e) {
this.log.error({ err: e }, 'private queue creation failed - restarting');
await Bluebird.delay(this.recovery.get('private', attempt));
return this.createPrivateQueue(attempt + 1);
}
this.log.debug({ queue: this._replyTo }, 'private-queue-ready');
setImmediate(this._boundEmit, 'private-queue-ready');
return createdQueue;
}
/**
*
* @param {string[]} routes
* @param {*} queue
* @param {*} oldQueue
* @returns
*/
async bindQueueToExchangeOnRoutes(routes, queue, oldQueue = Object.create(null)) {
/**
* @type {string[]}
*/
const previousRoutes = oldQueue._routes || [];
if (routes.length === 0 && previousRoutes.length === 0) {
queue._routes = [];
return;
}
// retrieved some of the routes
this.log.debug({ routes, previousRoutes }, 'retrieved routes');
const rebindRoutes = uniq([...previousRoutes, ...routes]);
queue._routes = rebindRoutes;
const work = [
this.bindExchange(queue, rebindRoutes, this.config.exchangeArgs),
];
// bind same queue to headers exchange
if (this.config.bindPersistantQueueToHeadersExchange === true) {
work.push(this.bindHeadersExchange(queue, rebindRoutes, this.config.headersExchange));
}
await Bluebird.all(work);
}
/**
* @param {Function} messageHandler
* @param {Array} listen
* @param {Object} options
*/
async createConsumedQueue(messageHandler, listen = [], options = {}) {
if (is.fn(messageHandler) === false || Array.isArray(listen) === false) {
throw new ArgumentError('messageHandler and listen must be present');
}
if (is.object(options) === false) {
throw new ArgumentError('options');
}
const { config } = this;
const router = initRoutingFn(messageHandler, this);
const baseOpts = {
router,
neck: config.neck,
noAck: config.noAck,
queue: config.queue || '',
};
const queueOptions = merge(
baseOpts,
config.defaultQueueOpts,
this._extraQueueOptions,
options
);
if (config.bindPersistantQueueToHeadersExchange === true) {
for (const route of listen.values()) {
assert.ok(
/^[^*#]+$/.test(route),
'with bindPersistantQueueToHeadersExchange: true routes must not have patterns'
);
}
}
// pipeline for establishing consumer
const establishConsumer = async (attempt = 0) => {
const { log, recovery } = this;
const {
_consumers: consumers,
_queues: queues,
_reconnectionHandlers: connectionHandlers,
} = this;
log.debug({ attempt }, 'establish consumer');
const oldConsumer = consumers.get(establishConsumer);
const oldQueue = queues.get(establishConsumer);
// if we have old consumer
if (oldConsumer) {
await this.closeConsumer(oldConsumer);
}
let createdQueue;
try {
const { queue } = createdQueue = await this.createQueue({ ...queueOptions });
await this.bindQueueToExchangeOnRoutes(listen, queue, oldQueue);
} catch (e) {
const err = new ConnectionError('failed to init queue or exchange', e);
log.warn({ err }, '[consumed-queue-down]');
await Bluebird.delay(recovery.get('consumed', attempt + 1));
return establishConsumer(attempt + 1);
}
const { consumer, queue } = createdQueue;
// save ref to WeakMap
consumers.set(establishConsumer, consumer);
queues.set(establishConsumer, queue);
connectionHandlers.set(consumer, establishConsumer);
// remove previous listeners if we re-use the channel
// for any reason
consumer.removeAllListeners('error');
consumer.removeAllListeners('cancel');
consumer.on('error', this.handleConsumerError.bind(this, consumer, queue));
consumer.on('cancel', this.rebindConsumer.bind(this, consumer));
// emit event that we consumer & queue is ready
const queueName = queue.queueOptions.queue;
log.info({ queueName, consumerTag: consumer.consumerTag }, 'consumed-queue-reconnected');
this.emit('consumed-queue-reconnected', consumer, queue, establishConsumer);
return queue.queueOptions.queue;
};
// make sure we recreate queue and establish consumer on reconnect
this.log.debug({ listen, queue: queueOptions.queue }, 'creating consumed queue');
const queueName = await establishConsumer();
this.log.debug({ listen, queue: queueName }, 'bound `ready` to establishConsumer');
this.on('ready', establishConsumer);
return establishConsumer;
}
/**
* Stops current running consumers
*/
async closeAllConsumers() {
const work = [];
for (const consumer of this._consumers.values()) {
work.push(this.stopConsumedQueue(consumer));
}
await Bluebird.all(work);
}
/**
* Utility function to close consumer and forget about it
* @param {Consumer} consumer
*/
async closeConsumer(consumer) {
this.log.warn('closing consumer', consumer.consumerTag);
// cleanup after one-self
this._consumers.delete(this._reconnectionHandlers.get(consumer));
this._reconnectionHandlers.delete(consumer);
consumer.removeAllListeners();
consumer.on('error', noop);
this._boundEmit('consumer-close', consumer);
// close channel
await Bluebird
.fromCallback((done) => {
consumer.cancel(done);
})
.timeout(5000)
.catch(Bluebird.TimeoutError, noop);
this.log.info({ consumerTag: consumer.consumerTag }, 'closed consumer');
}
/**
* Prevents consumer from re-establishing connection
* @param {Consumer} [consumer]
* @returns {Promise<Void>}
*/
async stopConsumedQueue(consumer) {
if (!consumer) {
throw new TypeError('consumer must be defined');
}
const establishConsumer = this._reconnectionHandlers.get(consumer);
this.log.debug({ establishConsumer: !!establishConsumer }, 'fetched establish consumer');
if (establishConsumer) {
this.removeListener('ready', establishConsumer);
}
await this.closeConsumer(consumer);
}
/**
* Declares exchange and reports 406 error.
* @param {Object} params - Exchange params.
* @returns {Bluebird<any>}
*/
declareExchange(params) {
return this._amqp
.exchangeAsync(params)
.call('declareAsync')
.catch(error406, this._on406.bind(this, params));
}
/**
* Binds exchange to queue via route. For Headers exchange
* automatically populates arguments with routing-key: <route>.
* @param {string} exchange - Exchange to bind to.
* @param {Queue} queue - Declared queue object.
* @param {string} route - Routing key.
* @param {string | boolean} [headerName=false] - if exchange has `headers` type.
* @returns {Promise<any>}
*/
async bindRoute(exchange, queue, route, headerName = false) {
const queueName = queue.queueOptions.queue;
const options = {};
let routingKey;
if (headerName === false) {
routingKey = route;
} else {
options.arguments = {
'x-match': 'any',
[headerName === true ? 'routing-key' : headerName]: route,
};
routingKey = '';
}
const response = await queue.bindAsync(exchange, routingKey, options);
const { _routes: routes } = queue;
if (Array.isArray(routes)) {
// reconnect might push an extra route
if (!routes.includes(route)) {
routes.push(route);
}
this.log.trace({ routes, queueName }, '[queue routes]');
}
this.log.debug({ queueName, exchange, routingKey }, 'bound queue to exchange');
return response;
}
/**
* Bind specified queue to exchange
*
* @param {object} queue - queue instance created by .createQueue
* @param {string | string[]} _routes - messages sent to this route will be delivered to queue
* @param {object} [opts={}] - exchange parameters:
* https://github.com/dropbox/amqp-coffee#connectionexchangeexchangeargscallback
*/
bindExchange(queue, _routes, opts = {}) {
// make sure we have an expanded array of routes
const routes = toUniqueStringArray(_routes);
// default params
const params = merge({
exchange: this.config.exchange,
type: this.config.exchangeArgs.type,
durable: true,
autoDelete: false,
}, opts);
const { exchange } = params;
assert(exchange, 'exchange name must be specified');
this.log.debug('bind routes->exchange', routes, exchange);
return this.declareExchange(params)
.return(routes)
.map((route) => (
this.bindRoute(exchange, queue, route)
));
}
/**
* Binds multiple routing keys to headers exchange.
* @param {Object} queue
* @param {string | string[]} _routes
* @param {Object} opts
* @param {string | boolean} [headerName=true] - if exchange has `headers` type
* @returns {Bluebird<*>}
*/
bindHeadersExchange(queue, _routes, opts, headerName = true) {
// make sure we have an expanded array of routes
const routes = toUniqueStringArray(_routes);
// default params
const params = merge({ durable: true, autoDelete: false }, opts);
const { exchange } = params;
// headers exchange
// do sanity check
assert.equal(params.type, 'headers');
assert.ok(exchange, 'exchange must be set');
this.log.debug('bind routes->exchange/headers', routes, exchange);
return this.declareExchange(params)
.return(routes)
.map((route) => {
assert.ok(/^[^*#]+$/.test(route));
return this.bindRoute(exchange, queue, route, headerName);
});
}
/**
* Unbind specified queue from exchange
*
* @param {object} queue - queue instance created by .createQueue
* @param {string | string[]} _routes - messages sent to this route will be delivered to queue
* @returns {Bluebird<any>}
*/
unbindExchange(queue, _routes) {
const { exchange } = this.config;
const routes = toUniqueStringArray(_routes);
return Bluebird.map(routes, (route) => (
queue.unbindAsync(exchange, route).tap(() => {
const queueName = queue.queueOptions.queue;
if (queue._routes) {
const idx = queue._routes.indexOf(route);
if (idx >= 0) {
queue._routes.splice(idx, 1);
}
this.log.debug({ routes: queue._routes }, 'queue routes');
}
this.log.info({ queueName, exchange, route }, 'queue unbound from exchange');
})
));
}
/**
* Low-level publishing method
* @param {string} exchange
* @param {string} queueOrRoute
* @param {any} _message
* @param {PublishOptions} options
* @returns {Promise<*>}
*/
async sendToServer(exchange, queueOrRoute, _message, options) {
const publishOptions = this._publishOptions(options);
const message = options.skipSerialize === true
? _message
: await serialize(_message, publishOptions);
const { _amqp: amqp } = this;
if (!amqp) {
// NOTE: if this happens - it means somebody
// called (publish|send)* after amqp.close()
// or there is an auto-retry policy that does the same
throw new InvalidOperationError('connection was closed');
}
const request = await amqp
.publishAsync(exchange, queueOrRoute, message, publishOptions);
// emit original message
this.emit('publish', queueOrRoute, _message);
return request;
}
/**
* Send message to specified route
*
* @template [T=any]
*
* @param {String} route - Destination route
* @param {any} message - Message to send - will be coerced to string via stringify
* @param {PublishOptions} [options={}] - Additional options
* @param {opentracing.Span} [parentSpan] - Existing span
* @returns {Bluebird<T>}
*/
publish(route, message, options = {}, parentSpan) {
const span = this.tracer.startSpan(`publish:${route}`, {
childOf: parentSpan,
});
// prepare exchange
const exchange = is.string(options.exchange)
? options.exchange
: this.config.exchange;
span.addTags({
[Tags.SPAN_KIND]: Tags.SPAN_KIND_MESSAGING_PRODUCER,
[Tags.MESSAGE_BUS_DESTINATION]: `${exchange}:${route}`,
});
return wrapPromise(span, this.sendToServer(
exchange,
route,
message,
options
));
}
/**
* Send message to specified queue directly
*
* @template [T=any]
*
* @param {String} queue - Destination queue
* @param {any} message - Message to send
* @param {PublishOptions} [options={}] - Additional options
* @param {opentracing.Span} [parentSpan] - Existing span
* @returns {Bluebird<T>}
*/
send(queue, message, options = {}, parentSpan) {
const span = this.tracer.startSpan(`send:${queue}`, {
childOf: parentSpan,
});
// prepare exchange
const exchange = is.string(options.exchange)
? options.exchange
: '';
span.addTags({
[Tags.SPAN_KIND]: Tags.SPAN_KIND_MESSAGING_PRODUCER,
[Tags.MESSAGE_BUS_DESTINATION]: `${exchange || '<empty>'}:${queue}`,
});
return wrapPromise(span, this.sendToServer(
exchange,
queue,
message,
options
));
}
/**
* Sends a message and then awaits for response
*
* @template [T=any]
*
* @param {String} route - Destination route
* @param {any} message - Message to send - will be coerced to string via stringify
* @param {PublishOptions} [options={}] - Additional options
* @param {opentracing.Span} [parentSpan] - Existing span
* @returns {Promise<T>}
*/
publishAndWait(route, message, options = {}, parentSpan) {
// opentracing instrumentation
const span = this.tracer.startSpan(`publishAndWait:${route}`, {
childOf: parentSpan,
});
span.addTags({
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_CLIENT,
[Tags.MESSAGE_BUS_DESTINATION]: route,
});
return wrapPromise(span, this.createMessageHandler(
route,
message,
options,
this.publish,
span
));
}
/**
* Send message to specified queue directly and wait for answer
* @template [T=any]
*
* @param {string} queue - Destination queue
* @param {any} message - Message to send
* @param {PublishOptions} [options={}] - Additional options
* @param {opentracing.Span} [parentSpan] - Existing span
* @returns {Bluebird<T>}
*/
sendAndWait(queue, message, options = {}, parentSpan) {
// opentracing instrumentation
const span = this.tracer.startSpan(`sendAndWait:${queue}`, {
childOf: parentSpan,
});
span.addTags({
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_CLIENT,
[Tags.MESSAGE_BUS_DESTINATION]: queue,
});
return wrapPromise(span, this.createMessageHandler(
queue,
message,
options,
this.send
));
}
/**
* Specifies default publishing options
* @param {PublishOptions} options
* @return {Object}
*/
_publishOptions(options = {}) {
// remove unused opts
const { skipSerialize, gzip: needsGzip, ...opts } = options;
// force contentEncoding
if (needsGzip === true) {
opts.contentEncoding = 'gzip';
}
// set default opts
defaults(opts, this._defaultOpts);
// append request timeout in headers
defaults(opts.headers, {
timeout: opts.timeout || this.config.timeout,
});
return opts;
}
_replyOptions(options = {}) {
return {
simpleResponse: options.simpleResponse === undefined
? this._defaultOpts.simpleResponse
: options.simpleResponse,
};
}
/**
* Reply to sender queue based on headers
*
* @param {Object} properties - incoming message headers
* @param {any} message - message to send
* @param {Span} [span] - opentracing span
* @param {AMQPMessage} [raw] - raw message
* @returns {Bluebird<any>}
*/
reply(properties, message, span, raw) {
if (!properties.replyTo || !properties.correlationId) {
const error = new HttpStatusError(400, 'replyTo and correlationId not found in properties');
if (span !== undefined) {
span.setTag(Tags.ERROR, true);
span.log({
event: 'error', 'error.object': error, message: error.message, stack: error.stack,
});
span.finish();
}
if (raw !== undefined) {
this.emit('after', raw);
}
return Bluebird.reject(error);
}
/**
* @type {PublishOptions}
*/
const options = {
correlationId: properties.correlationId,
};
if (properties[kReplyHeaders]) {
options.headers = properties[kReplyHeaders];
}
let promise = this.send(properties.replyTo, message, options, span);
if (raw !== undefined) {
promise = promise
.finally(() => this.emit('after', raw));
}
return span === undefined
? promise
: wrapPromise(span, promise);
}
/**
* Creates local listener for when a private queue is up
* @returns {Promise<void>}
*/
async awaitPrivateQueue() {
await once(this, 'private-queue-ready');
}
/**
* Creates response message handler and sets timeout on the response
* @param {String} routing
* @param {Object} options
* @param {String} message
* @param {Function} publishMessage
* @param {Span} [span] - opentracing span
* @return {Promise}
*/
async createMessageHandler(routing, message, options, publishMessage, span) {
assert(typeof options === 'object' && options !== null, 'options must be an object');
const replyTo = options.replyTo || this._replyTo;
const time = process.hrtime();
const replyOptions = this._replyOptions(options);
// ensure that reply queue exists before sending request
if (typeof replyTo !== 'string') {
if (replyTo === false) {
await this.awaitPrivateQueue();
} else {
await this.createPrivateQueue();
}
return this.createMessageHandler(routing, message, options, publishMessage, span);
}
// work with cache if options.cache is set and is number
// otherwise cachedResponse is always null
const cachedResponse = this.cache.get(message, options.cache);
if (cachedResponse !== null && typeof cachedResponse === 'object') {
return adaptResponse(cachedResponse.value, replyOptions);
}
const { replyStorage } = this;
// generate response id
const correlationId = options.correlationId || uuid.v4();
// timeout before RPC times out
const timeout = options.timeout || this.config.timeout;
// slightly longer timeout, if message was not consumed in time, it will return with expiration
const publishPromise = new Promise((resolve, reject) => {
// push into RPC request storage
replyStorage.push(correlationId, {
timeout,
time,
routing,
resolve,
reject,
replyOptions,
cache: cachedResponse,
timer: null,
});
});
// debugging
this.log.trace('message pushed into reply queue in %s', latency(time));
// add custom header for routing over amq.headers exchange
if (!options.headers) {
options.headers = Object.create(null);
}
options.headers['reply-to'] = replyTo;
// add opentracing instrumentation
if (span) {
this.tracer.inject(span.context(), FORMAT_TEXT_MAP, options.headers);
}
// this is to ensure that queue is not overflown and work will not
// be completed later on
publishMessage
.call(this, routing, message, {
...options,
replyTo,
correlationId,
expiration: Math.ceil(timeout * 0.9).toString(),
}, span)
.tap(() => {
this.log.trace({ latency: latency(time) }, 'message published');
})
.catch((err) => {
this.log.error({ err }, 'error sending message');
replyStorage.reject(correlationId, err);
});
return publishPromise;
}
/**
*
*/
_onConsume(_router) {
assert(is.fn(_router), '`router` must be a function');
// use bind as it is now fast
const amqpTransport = this;
const parseInput = amqpTransport._parseInput.bind(amqpTransport);
const router = _router.bind(amqpTransport);
/**
* @param {Object} incoming
* @param {Object} incoming.data: a getter that returns the data in its parsed form, eg a
* parsed json object, a string, or the raw buffer
* @param {AMQPMessage['properties']} incoming.properties
* @param {AMQPMessage} incoming.raw
*/
return async function consumeMessage(incoming) {
// emit pre processing hook
amqpTransport.emit('pre', incoming);
// extract message data
const { properties } = incoming;
const { contentType, contentEncoding } = properties;
// parsed input data
const message = await parseInput(incoming.raw, contentType, contentEncoding);
// useful message properties
const props = { ...properties, ...pick(incoming, extendMessageProperties) };
// pass to the consumer message router
// message - properties - incoming
// incoming.raw<{ ack: ?Function, reject: ?Function, retry: ?Function }>
// and everything else from amqp-coffee
setImmediate(router, message, props, incoming);
};
}
/**
* Distributes messages from a private queue
* @param {any} message
* @param {AMQPMessage['properties']} properties
*/
_privateMessageRouter(message, properties/* , raw */) { // if private queue has nack set - we must ack msg
const { correlationId, replyTo, headers } = properties;
const { 'x-death': xDeath } = headers;
// retrieve promised message
const future = this.replyStorage.pop(correlationId);
// case 1 - for some reason there is no saved reference, example - crashed process
if (future === undefined) {
this.log.error('no recipient for the message %j and id %s', message.error || message.data || message, correlationId);
let error;
if (xDeath) {
error = new AmqpDLXError(xDeath, message);
this.log.warn({ err: error }, 'message was not processed');
}
// otherwise we just run messages in circles
if (replyTo && replyTo !== this._replyTo) {
// if error is undefined - generate this
if (error === undefined) {
error = new NotPermittedError(`no recipients found for correlationId "${correlationId}"`);
}
// reply with the error
return this.reply(properties, { error });
}
// we are done
return null;
}
this.log.trace('response returned in %s', latency(future.time));
// if message was dead-lettered - reject with an error
if (xDeath) {
return future.reject(new AmqpDLXError(xDeath, message));
}
if (message.error) {
const error = wrapError(message.error);
Object.defineProperty(error, kReplyHeaders, {
value: headers,
enumerable: false,
});
return future.reject(error);
}
const response = buildResponse(message, properties);
this.cache.set(future.cache, response);
return future.resolve(adaptResponse(response, future.replyOptions));
}
/**
* Parses AMQP message
* @template [T=any]
* @param {Buffer} _data
* @param {String} [contentType='application/json']
* @param {String} [contentEncoding='plain']
* @return {Promise<T | { err: Error }>}
*/
async _parseInput(_data, contentType = 'application/json', contentEncoding = 'plain') {
let data;
switch (contentEncoding) {
case 'gzip':
data = await gunzip(_data).catchReturn({ err: PARSE_ERR });
break;
case 'plain':
data = _data;
break;
default:
return { err: PARSE_ERR };
}
switch (contentType) {
// default encoding when we were pre-stringifying and sending str
// and our updated encoding when we send buffer now
case 'string/utf8':
case 'application/json':
return safeJSONParse(data, this.log);
default:
return data;
}
}
/**
* Handle 406 Error.
* @param {Object} params - exchange params
* @param {AMQPError} err - 406 Conflict Error.
*/
_on406(params, err) {
this.log.warn({ params }, '[406] error declaring exchange/queue: %s', err.replyText);
}
/**
* 'ready' event from amqp-coffee lib, perform queue recreation here
*/
_onConnect() {
const { serverProperties } = this._amqp;
const { cluster_name: clusterName, version } = serverProperties;
// emit connect event through log
this.log.info('connected to %s v%s', clusterName, version);
// https://github.com/dropbox/amqp-coffee#reconnect-flow
// recreate unnamed private queue
if ((this._replyTo || this.config.private) && this._replyTo !== false) {
this.createPrivateQueue();
}
// re-emit ready
this.emit('ready');
}
/**
* Pass in close event
*/
_onClose(err) {
// emit connect event through log
this.log.warn({ err }, 'connection is closed');
// re-emit close event
this.emit('close', err);
}
}
/**
* Creates AMQPTransport instance
* @template {Function} T
* @param {Object} [_config]
* @param {T} [_messageHandler]
* @returns {Bluebird<[AMQPTransport, T]>}
*/
AMQPTransport.create = function create(_config, _messageHandler) {
let config;
let messageHandler;
if (is.fn(_config) && is.undefined(_messageHandler)) {
messageHandler = _config;
config = {};
} else {
messageHandler = _messageHandler;
config = _config;
}
// init AMQP connection
const amqp = new AMQPTransport(config);
// connect & resolve AMQP connector & message handler if it exists
return amqp.connect().return([amqp, messageHandler]);
};
/**
* Allows one to consume messages with a given router and predefined callback handler
* @param {Record<string, any>} config
* @param {Function} [_messageHandler]
* @param {Object} [_opts={}]
* @returns {Bluebird<AMQPTransport>}
*/
AMQPTransport.connect = function connect(config, _messageHandler, _opts = {}) {
return AMQPTransport
.create(config, _messageHandler)
.then(async ([amqp, messageHandler]) => {
// do not init queues
if (is.fn(messageHandler) !== false || amqp.config.listen) {
await amqp.createConsumedQueue(messageHandler, amqp.config.listen, _opts);
}
return amqp;
});
};
/**
* Same as AMQPTransport.connect, except that it creates a queue
* per each of the routes we want to listen to
* @param {Object} config
* @param {Function} [_messageHandler]
* @param {Object} [opts={}]
* @returns {Bluebird<AMQPTransport>}
*/
AMQPTransport.multiConnect = function multiConnect(config, _messageHandler, opts = []) {
return AMQPTransport
.create(config, _messageHandler)
.then(async ([amqp, messageHandler]) => {
// do not init queues
if (is.fn(messageHandler) === false && !amqp.config.listen) {
return amqp;
}
await Bluebird.map(amqp.config.listen, (route, idx) => {
const queueOpts = opts[idx] || Object.create(null);
const queueName = config.queue
? `${config.queue}-${route.replace(/[#*]/g, '.')}`
: config.queue;
const consumedQueueOpts = defaults(queueOpts, {
queue: queueName,
});
return amqp.createConsumedQueue(messageHandler, [route], consumedQueueOpts);
});
return amqp;
});
};
// expose internal libraries
AMQPTransport.ReplyStorage = ReplyStorage;
AMQPTransport.Backoff = Backoff;
AMQPTransport.Cache = Cache;
AMQPTransport.jsonSerializer = jsonSerializer;
AMQPTransport.jsonDeserializer = jsonDeserializer;
// assign statics
module.exports = AMQPTransport;
<file_sep>const baseJoi = require('joi');
const recoverySchema = require('./utils/recovery').schema;
const Joi = baseJoi.extend((joi) => ({
type: 'coercedArray',
base: joi.alternatives().try(
joi.array().items(joi.string()).unique(),
joi.string()
),
validate(value) {
if (typeof value === 'string') {
return { value: [value] };
}
return { value };
},
}));
const exchangeTypes = Joi.string()
.valid('direct', 'topic', 'headers', 'fanout');
exports.Joi = Joi;
exports.schema = Joi
.object({
name: Joi.string()
.description('name of the service when advertising to AMQP')
.default('amqp'),
private: Joi.boolean()
.description('when true - initializes private queue right away')
.default(false),
cache: Joi.number().min(0)
.description('size of LRU cache for responses, 0 to disable it')
.default(100),
timeout: Joi.number()
.description('default *AndWait timeout')
.default(10000),
debug: Joi.boolean()
.description('enables debug messages')
.default(process.env.NODE_ENV !== 'production'),
listen: Joi.coercedArray()
.description('attach default queue to these routes on default exchange'),
version: Joi.string()
.description('advertise end-client service version')
.default('n/a'),
neck: Joi.number().min(0)
.description('if defined - queues will enter QoS mode with required ack & prefetch size of neck'),
noAck: Joi.boolean()
.description('allow setting auto-ack when neck is defined'),
tracer: Joi.object(),
connection: Joi
.object({
host: Joi.alternatives()
.try(
Joi.string(),
Joi.array().min(1).items(Joi.string()),
Joi.array().min(1).items(Joi.object({
host: Joi.string().required(),
port: Joi.number().required(),
}))
)
.description('rabbitmq host')
.default('localhost'),
port: Joi.number()
.description('rabbitmq port')
.default(5672),
heartbeat: Joi.number()
.description('heartbeat check')
.default(10000),
login: Joi.string()
.description('rabbitmq login')
.default('guest'),
password: Joi.string()
.description('rabbitmq password')
.default('<PASSWORD>'),
vhost: Joi.string()
.description('rabbitmq virtual host')
.default('/'),
temporaryChannelTimeout: Joi.number()
.description('temporary channel close time with no activity')
.default(6000),
reconnect: Joi.boolean()
.description('enable auto-reconnect')
.default(true),
reconnectDelayTime: Joi.number()
.description('reconnect delay time')
.default(500),
hostRandom: Joi.boolean()
.description('select host to connect to randomly')
.default(false),
ssl: Joi.boolean()
.description('whether to use SSL')
.default(false),
sslOptions: Joi.object()
.description('ssl options'),
noDelay: Joi.boolean()
.description('disable Nagle\'s algorithm')
.default(true),
clientProperties: Joi
.object({
capabilities: Joi.object({
consumer_cancel_notify: Joi.boolean()
.description('whether to react to cancel events')
.default(true),
}).default(),
})
.description('options for advertising client properties')
.default(),
})
.description('options for setting up connection to RabbitMQ')
.default(),
recovery: recoverySchema
.description('recovery settings')
.default(),
exchange: Joi.string()
.allow('')
.description('default exchange for communication')
.default('node-services'),
exchangeArgs: Joi
.object({
autoDelete: Joi.boolean()
.description('do not autoDelete exchanges')
.default(false),
noWait: Joi.boolean()
.description('whether not to wait for declare response')
.default(false),
internal: Joi.boolean()
.description('whether to set internal bit')
.default(false),
type: exchangeTypes
.description('type of the exchange')
.default('topic'),
durable: Joi.boolean()
.description('whether to preserve exchange on rabbitmq restart')
.default(true),
})
.default(),
bindPersistantQueueToHeadersExchange: Joi.boolean()
.description('whether to bind queues created by .createConsumedQueue to headersExchange')
.default(false),
headersExchange: Joi
.object({
exchange: Joi.string()
.description('default headers exchange to use, should be different from DLX headers exchange')
.default('amq.match'),
autoDelete: Joi.boolean()
.description('do not autoDelete exchanges')
.default(false),
noWait: Joi.boolean()
.description('whether not to wait for declare response')
.default(false),
internal: Joi.boolean()
.description('whether to set internal bit')
.default(false),
type: Joi.string()
.valid('headers')
.description('type of the exchange')
.default('headers'),
durable: Joi.boolean()
.description('whether to preserve exchange on rabbitmq restart')
.default(true),
})
.description('this exchange is used to support delayed retry with QoS exchanges')
.default(),
queue: Joi.string()
.description('default queue to connect to for consumption'),
defaultQueueOpts: Joi
.object({
autoDelete: Joi.boolean(),
exclusive: Joi.boolean(),
noWait: Joi.boolean(),
passive: Joi.boolean(),
durable: Joi.boolean()
.description('survive restarts & use disk storage')
.default(true),
arguments: Joi
.object({
'x-expires': Joi.number().min(0)
.description('delete queue after it\'s been unused for X seconds'),
'x-max-priority': Joi.number().min(2).max(255)
.description('setup priority queues where messages will be delivery based on priority level'),
})
.default(),
})
.description('default options for creating consumer queues')
.default(),
privateQueueOpts: Joi
.object({
autoDelete: Joi.boolean(),
exclusive: Joi.boolean(),
noWait: Joi.boolean(),
passive: Joi.boolean(),
durable: Joi.boolean()
.description('survive restarts & use disk storage')
.default(true),
arguments: Joi
.object({
'x-expires': Joi.number().min(0)
.description('delete the private queue after it\'s been unused for 3 minutes')
.default(1800000),
'x-max-priority': Joi.number().min(2).max(255)
.description('setup priority queues where messages will be delivery based on priority level'),
})
.default(),
})
.description('default options for private RPC queues')
.default(),
dlx: Joi
.object({
enabled: Joi.boolean()
.description('enabled DLX by default for fast-reply when messages are dropped')
.default(true),
params: Joi
.object({
exchange: Joi.string()
.description('dead letters are redirected here')
.default('amq.headers'),
type: exchangeTypes
.description('must be headers for proper built-in matching')
.default('headers'),
autoDelete: Joi.boolean()
.description('DLX persistance')
.default(false),
})
.default(),
})
.description('default for dead-letter-exchange')
.default(),
defaultOpts: Joi
.object({
deliveryMode: Joi.number().valid(1, 2)
.description('1 - transient, 2 - saved on disk')
.default(1),
confirm: Joi.boolean()
.description('whether to wait for commit confirmation')
.default(false),
mandatory: Joi.boolean()
.description('when true and message cant be routed to a queue - exception returned, otherwise its dropped')
.default(false),
immediate: Joi.boolean()
.description('not implemented by rabbitmq')
.default(false),
contentType: Joi.string()
.default('application/json')
.description('default content-type for messages'),
contentEncoding: Joi.string()
.default('plain')
.description('default content-encoding'),
headers: Joi.object()
.default(),
simpleResponse: Joi.boolean()
.description('whether to return only response data or include headers etc.')
.default(true),
})
.description('default options when publishing messages')
.default(),
})
.assert(
'.dlx.params.exchange',
Joi.any().invalid(Joi.ref('headersExchange.exchange')),
'must use different headers exchanges'
);
<file_sep>// eslint-disable-next-line max-classes-per-file
const Promise = require('bluebird');
const { HttpStatusError, Error: CommonError } = require('common-errors');
const Proxy = require('@microfleet/amqp-coffee/test/proxy').route;
const ld = require('lodash');
const stringify = require('json-stringify-safe');
const sinon = require('sinon');
const assert = require('assert');
const microtime = require('microtime');
const { MockTracer } = require('opentracing/lib/mock_tracer');
const debug = require('debug')('amqp');
// add inject/extract implementation
MockTracer.prototype._inject = (span, format, carrier) => {
carrier['x-mock-span-uuid'] = span._span.uuid();
};
MockTracer.prototype._extract = function extract(format, carrier) {
return this.report().spansByUUID[carrier['x-mock-span-uuid']];
};
/* eslint-disable no-restricted-syntax */
const printReport = (report) => {
const reportData = ['Spans:'];
for (const span of report.spans) {
const tags = span.tags();
const tagKeys = Object.keys(tags);
reportData.push(` ${span.operationName()} - ${span.durationMs()}ms`);
for (const key of tagKeys) {
const value = tags[key];
reportData.push(` tag '${key}':'${value}'`);
}
}
if (report.unfinishedSpans.length > 0) reportData.push('Unfinished:');
for (const unfinishedSpan of report.unfinishedSpans) {
const tags = unfinishedSpan.tags();
const tagKeys = Object.keys(tags);
reportData.push(` ${unfinishedSpan.operationName()} - ${unfinishedSpan.durationMs()}ms`);
for (const key of tagKeys) {
const value = tags[key];
reportData.push(` tag '${key}':'${value}'`);
}
}
return reportData.join('\n');
};
/* eslint-enable no-restricted-syntax */
describe('AMQPTransport', function AMQPTransportTestSuite() {
// require module
const AMQPTransport = require('../src');
const { AmqpDLXError } = require('../src/utils/error');
const { jsonSerializer, jsonDeserializer } = require('../src/utils/serialization');
const latency = require('../src/utils/latency');
const { kReplyHeaders } = require('../src/constants');
const RABBITMQ_HOST = process.env.RABBITMQ_PORT_5672_TCP_ADDR || 'localhost';
const RABBITMQ_PORT = +(process.env.RABBITMQ_PORT_5672_TCP_PORT || 5672);
const configuration = {
exchange: 'test-exchange',
connection: {
host: RABBITMQ_HOST,
port: RABBITMQ_PORT,
},
};
it('stringifies message correctly', () => {
this.originalMsg = {
meta: {
controlsData: [
0.25531813502311707, 0.0011256206780672073, 0.06426551938056946,
-0.001104108989238739, 0.852259635925293, 0.005791602656245232,
-0.5230863690376282, 0, 0.9999388456344604, 0.011071242392063141,
0.523118257522583, -0.009435615502297878, 0.8522077798843384,
0.8522599935531616, 0, 0.5231184363365173, 0, 0.005791574250906706,
0.9999387264251709, -0.009435582906007767, 0, -0.5230863690376282,
0.011071248911321163, 0.8522077798843384, 0, -0.13242781162261963,
0.06709221005439758, 0.21647998690605164, 1,
],
name: 'oki-dokie',
},
body: {
random: true,
data: [{
filename: 'ok',
version: 10.3,
}],
},
buffer: Buffer.from('xxx'),
};
this.msg = stringify(this.originalMsg, jsonSerializer);
// eslint-disable-next-line max-len
assert.equal(this.msg, '{"meta":{"controlsData":[0.25531813502311707,0.0011256206780672073,0.06426551938056946,-0.001104108989238739,0.852259635925293,0.005791602656245232,-0.5230863690376282,0,0.9999388456344604,0.011071242392063141,0.523118257522583,-0.009435615502297878,0.8522077798843384,0.8522599935531616,0,0.5231184363365173,0,0.005791574250906706,0.9999387264251709,-0.009435582906007767,0,-0.5230863690376282,0.011071248911321163,0.8522077798843384,0,-0.13242781162261963,0.06709221005439758,0.21647998690605164,1],"name":"oki-dokie"},"body":{"random":true,"data":[{"filename":"ok","version":10.3}]},"buffer":{"type":"Buffer","data":[120,120,120]}}');
});
it('deserializes message correctly', () => {
assert.deepEqual(JSON.parse(this.msg, jsonDeserializer), this.originalMsg);
});
it('serializes & deserializes error', () => {
const serialized = stringify(new Error('ok'), jsonSerializer);
const err = JSON.parse(serialized, jsonDeserializer);
assert.equal(err.name, 'MSError');
assert.equal(!!err.stack, true);
assert.equal(err.message, 'ok');
assert.ok(err.constructor);
});
// See usage at:
// https://github.com/microfleet/core/blob/f252a71e2947696f21d82830e2714b51aa4d8703/packages/plugin-router/src/lifecycle/handlers/response.ts#L58
it('serializes & deserializes error wrapped with `common-errors` error', () => {
class MyError extends Error {
// eslint-disable-next-line no-useless-constructor
constructor(message) {
super(message);
this.data = { some: 'data' };
}
}
class MyBadError extends MyError {}
const serialized = stringify(new CommonError('Wrapper', new MyBadError('ok')), jsonSerializer);
const err = JSON.parse(serialized, jsonDeserializer);
assert.equal(err.name, 'Error');
assert.equal(!!err.stack, true);
assert.equal(err.message, 'Wrapper');
assert.deepStrictEqual(err.inner_error.data, { some: 'data' });
assert.ok(err.constructor);
assert.ok(err.inner_error.constructor);
});
it('serializes & deserializes http status error', () => {
const serialized = stringify(new HttpStatusError(202, 'ok'), jsonSerializer);
const err = JSON.parse(serialized, jsonDeserializer);
assert.equal(err.name, 'HttpStatusError');
assert.equal(!!err.stack, true);
assert.equal(err.message, 'ok');
assert.equal(err.statusCode, 202);
assert.equal(err.status_code, 202);
});
it('is able to be initialized', () => {
const amqp = new AMQPTransport(configuration);
assert(amqp instanceof AMQPTransport);
assert(amqp.config, 'config defined');
assert(amqp.replyStorage, 'reply storage initialized');
assert(amqp.cache, 'cache storage initialized');
});
it('fails on invalid configuration', () => {
function createTransport() {
return new AMQPTransport({
name: {},
private: 'the-event',
exchange: '',
timeout: 'don-don',
connection: 'bad option',
});
}
assert.throws(createTransport, 'ValidationError');
});
it('is able to connect to rabbitmq', async () => {
const amqp = this.amqp = new AMQPTransport(configuration);
await amqp.connect();
assert.equal(amqp._amqp.state, 'open');
});
it('is able to disconnect', async () => {
await this.amqp.close();
assert.equal(this.amqp._amqp, null);
});
it('is able to connect via helper function', async () => {
const amqp = await AMQPTransport.connect(configuration);
assert.equal(amqp._amqp.state, 'open');
this.amqp = amqp;
});
it('is able to consume routes', async () => {
const opts = {
cache: 100,
exchange: configuration.exchange,
queue: 'test-queue',
listen: ['test.default', 'test.throw'],
connection: configuration.connection,
};
const amqp = await AMQPTransport.connect(opts, (message, properties, actions, callback) => {
if (properties.routingKey === 'test.throw') {
return callback(new HttpStatusError(202, 'ok'));
}
return callback(null, {
resp: typeof message === 'object' ? message : `${message}-response`,
time: process.hrtime(),
});
});
assert.equal(amqp._amqp.state, 'open');
this.amqp_consumer = amqp;
});
after('cleanup', async () => (
Promise.map(['amqp', 'amqp_consumer'], (name) => (
this[name] && this[name].close()
))
));
it('error is correctly deserialized', async () => {
await assert.rejects(this.amqp.publishAndWait('test.throw', {}), {
name: 'HttpStatusError',
message: 'ok',
statusCode: 202,
status_code: 202,
});
});
it('is able to publish to route consumer', async () => {
const response = await this.amqp
.publishAndWait('test.default', 'test-message');
assert.equal(response.resp, 'test-message-response');
});
it('is able to publish to route consumer:2', async () => {
const response = await this.amqp
.publishAndWait('test.default', 'test-message');
assert.equal(response.resp, 'test-message-response');
});
it('is able to publish to route consumer:2', async () => {
const response = await this.amqp
.publishAndWait('test.default', 'test-message');
assert.equal(response.resp, 'test-message-response');
});
it('is able to send messages directly to a queue', async () => {
const privateQueue = this.amqp._replyTo;
const promise = await this.amqp_consumer
.sendAndWait(privateQueue, 'test-message-direct-queue')
.reflect();
assert.equal(promise.isRejected(), true);
assert.equal(promise.reason().name, 'NotPermittedError');
});
describe('concurrent publish', () => {
before('init consumer', () => {
const transport = this.concurrent = new AMQPTransport(configuration);
return transport.connect();
});
it('able to publish multiple messages at once', () => {
const transport = this.concurrent;
const promises = ld.times(5, (i) => (
transport.publishAndWait('test.default', `ok.${i}`)
));
return Promise.all(promises);
});
after('close consumer', async () => {
await this.concurrent.close();
});
});
describe('DLX: enabled', () => {
before('init amqp', () => {
const transport = this.dlx = new AMQPTransport(configuration);
return transport.connect();
});
after('close amqp', async () => {
await this.dlx.close();
});
it('create queue, but do not consume', async () => {
const kReestablishQueue = await this.dlx.createConsumedQueue(() => {}, ['hub'], {
queue: 'dlx-consumer',
});
await this.dlx._consumers.get(kReestablishQueue).close();
});
it('publish message and receive DLX response', () => (
// it will be published to the `dlx-consumer` queue
// and after 2250 ms moved to '' with routing key based on the
// headers values
this.dlx
.publishAndWait('hub', { wont: 'be-consumed-queue' }, {
// set smaller timeout than 10s so we don't wait
// resulting x-message-ttl is 80% (?) of timeout
timeout: 2500,
})
.throw(new Error('did not reject'))
.catch(AmqpDLXError, (e) => {
assert.equal(e.message, 'Expired from queue "dlx-consumer" with routing keys ["hub"] after 2250ms 1 time(s)');
})
));
});
describe('cached request', () => {
before('init consumer', () => {
const transport = this.cached = new AMQPTransport(configuration);
return transport.connect();
});
after('close published', async () => {
await this.cached.close();
});
it('publishes batches of messages, they must return cached values and then new ones', () => {
const transport = this.cached;
const publish = () => transport.publishAndWait('test.default', 1, { cache: 2000 });
const promises = [
publish(),
Promise.delay(300).then(publish),
Promise.delay(5000).then(publish),
];
return Promise.all(promises).spread((initial, cached, nonCached) => {
const { toMiliseconds } = latency;
assert.equal(toMiliseconds(initial.time), toMiliseconds(cached.time));
assert(toMiliseconds(initial.time) < toMiliseconds(nonCached.time));
});
});
});
describe('contentEncoding, contentType', () => {
const gzip = Promise.promisify(require('zlib').gzip);
let transport;
before('init publisher', async () => {
transport = await AMQPTransport.connect(configuration);
});
after('close publisher', () => transport.close());
it('parses application/json+gzip', async () => {
let response;
const original = {
sample: true,
buf: Buffer.from('content'),
};
// send pre-serialized datum with gzip
response = await transport.publishAndWait(
'test.default',
await gzip(JSON.stringify(original)),
{
skipSerialize: true,
contentEncoding: 'gzip',
}
);
assert.deepStrictEqual(response.resp, original);
// pre-serialize no-gzip
response = await transport.publishAndWait(
'test.default',
Buffer.from(JSON.stringify(original)),
{ skipSerialize: true }
);
assert.deepStrictEqual(response.resp, original);
// not-serialized
response = await transport.publishAndWait('test.default', original);
assert.deepStrictEqual(response.resp, original);
// not-serialized + gzip
response = await transport.publishAndWait('test.default', original, { gzip: true });
assert.deepStrictEqual(response.resp, original);
});
});
describe('AMQPTransport.multiConnect', () => {
let acksCalled = 0;
const preCount = sinon.spy();
const postCount = sinon.spy();
const conf = {
exchange: configuration.exchange,
connection: configuration.connection,
queue: 'multi',
listen: ['t.#', 'tbone', 'morgue'],
};
after('close multi-transport', async () => {
await this.multi.close();
await this.publisher.close();
});
it('initializes amqp instance', () => {
// mirrors all messages
const spy = this.spy = sinon.spy(function listener(message, headers, actions, callback) {
acksCalled += 1;
actions.ack();
callback(null, message);
});
// adds QoS for the first queue, but not all the others
const consumer = AMQPTransport.multiConnect(conf, spy, [{
neck: 1,
}]);
const publisher = AMQPTransport.connect(configuration);
return Promise.join(consumer, publisher, (multi, amqp) => {
this.multi = multi;
this.publisher = amqp;
this.multi.on('pre', preCount);
this.multi.on('after', postCount);
});
});
it('verify that messages are all received & acked', async () => {
const q1 = Array.from({ length: 100 }).map((_, idx) => ({
route: `t.${idx}`,
message: `t.${idx}`,
}));
const q2 = Array.from({ length: 20 }).map((_, idx) => ({
route: 'tbone',
message: `tbone.${idx}`,
}));
const q3 = Array.from({ length: 30 }).map((_, idx) => ({
route: 'morgue',
message: `morgue.${idx}`,
}));
const pub = [...q1, ...q2, ...q3];
const responses = await Promise
.map(pub, (message) => (
this.publisher.publishAndWait(message.route, message.message)
))
.delay(10); // to allow async action to call 'after'
assert.equal(acksCalled, pub.length); // all messages have .ack now
// ensure all responses match
pub.forEach((p, idx) => {
assert.equal(responses[idx], p.message);
});
assert.equal(this.spy.callCount, pub.length);
// ensure that pre & after are called for each message
assert.equal(preCount.callCount, pub.length);
assert.equal(postCount.callCount, pub.length);
});
});
describe('priority queue', function test() {
const conf = {
exchange: configuration.exchange,
connection: configuration.connection,
queue: 'priority',
};
it('initializes amqp instance', () => {
// mirrors all messages
const consumer = AMQPTransport.connect(conf);
const publisher = AMQPTransport.connect(configuration);
return Promise.join(consumer, publisher, (priority, amqp) => {
this.priority = priority;
this.publisher = amqp;
});
});
after('close priority-transport', async () => {
await this.priority.close();
await this.publisher.close();
});
it('create priority queue', () => {
return this.priority
.createQueue({
queue: 'priority',
arguments: {
'x-max-priority': 5,
},
})
.then(({ queue }) => (
this.priority.bindExchange(queue, ['priority'], this.priority.config.exchangeArgs)
));
});
it('prioritize messages', () => {
const messages = Array.from({ length: 3 }).map((_, idx) => ({
message: idx % 4,
priority: idx % 4,
}));
const spy = sinon.spy(function listener(message, headers, actions, callback) {
actions.ack();
callback(null, microtime.now());
});
const publish = Promise.map(messages, ({ message, priority }) => {
return this.publisher.publishAndWait('priority', message, { priority, confirm: true, timeout: 60000 });
});
const consume = Promise.delay(500).then(() => this.priority.createConsumedQueue(spy, ['priority'], {
neck: 1,
arguments: {
'x-max-priority': 5,
},
}));
return Promise.join(publish, consume, (data) => {
data.forEach((micro, idx) => {
if (data[idx + 1]) assert.ok(micro > data[idx + 1]);
});
});
});
});
describe('double bind', function test() {
before('init transport', async () => {
this.spy = sinon.spy(function responder(message, properties, actions, next) {
next(null, { message, properties });
});
const opts = {
connection: {
...configuration.connection,
port: 5672,
heartbeat: 2000,
},
exchange: 'test-topic',
exchangeArgs: {
autoDelete: false,
type: 'topic',
},
defaultQueueOpts: {
autoDelete: false,
exclusive: false,
},
queue: 'nom-nom',
bindPersistantQueueToHeadersExchange: true,
listen: ['direct-binding-key', 'test.mandatory'],
};
this.transport = await AMQPTransport.connect(opts, this.spy);
});
after('close transport', async () => {
await this.transport.close();
});
it('delivers messages using headers', async () => {
await Promise
.map(['direct-binding-key', 'doesnt-exist'], (routingKey) => (
this.transport
.publish('', 'hi', {
confirm: true,
exchange: 'amq.match',
headers: {
'routing-key': routingKey,
},
})
.reflect()
))
.delay(100);
assert.ok(this.spy.calledOnce);
});
});
describe('Consumers externally available', function suite() {
before('init transport', async () => {
this.proxy = new Proxy(9010, RABBITMQ_PORT, RABBITMQ_HOST);
this.transport = new AMQPTransport({
connection: {
port: 9010,
heartbeat: 2000,
},
debug: true,
exchange: 'test-direct',
exchangeArgs: {
autoDelete: false,
type: 'direct',
},
defaultQueueOpts: {
autoDelete: true,
exclusive: true,
},
});
const amqp = await this.transport.connect();
sinon.spy(amqp, 'closeAllConsumers');
});
after('close transport', async () => {
const { transport } = this;
transport.closeAllConsumers.restore();
await transport.close();
await this.proxy.close();
});
function router(message, headers, actions, next) {
switch (headers.routingKey) {
case '/':
// #3 all right, try answer
assert.deepEqual(message, { foo: 'bar' });
return next(null, { bar: 'baz' });
default:
throw new Error();
}
}
it('`consumers` map filled', async () => {
const { transport } = this;
await transport.createConsumedQueue(router, ['/']);
const { _consumers } = transport;
assert.strictEqual(_consumers.size, 1);
await transport.closeAllConsumers();
assert.equal(_consumers.size, 0);
});
});
describe('consumed queue', function test() {
const tracer = new MockTracer();
before('init transport', async () => {
this.proxy = new Proxy(9010, RABBITMQ_PORT, RABBITMQ_HOST);
this.transport = new AMQPTransport({
connection: {
port: 9010,
heartbeat: 2000,
},
debug: true,
exchange: 'test-direct',
exchangeArgs: {
autoDelete: false,
type: 'direct',
},
defaultQueueOpts: {
autoDelete: true,
exclusive: true,
},
tracer,
});
await this.transport.connect();
});
afterEach('tracer report', () => {
const report = tracer.report();
// print report for visuals
console.log(printReport(report)); // eslint-disable-line no-console
assert.equal(report.unfinishedSpans.length, 0);
tracer.clear();
});
after('close transport', async () => {
await this.transport.close();
await this.proxy.close();
});
function router(message, headers, actions, next) {
switch (headers.routingKey) {
case '/':
// #3 all right, try answer
assert.deepEqual(message, { foo: 'bar' });
return next(null, { bar: 'baz' });
default:
throw new Error();
}
}
it('reestablishing consumed queue', async () => {
const { transport } = this;
const sample = { foo: 'bar' };
const publish = () => transport.publishAndWait('/', sample, { confirm: true });
let counter = 0;
const args = [];
transport.on('publish', (route, msg) => {
if (route === '/') {
args.push(msg);
counter += 1;
} else {
counter += 1;
}
});
try {
const kReestablishConsumer = await transport.createConsumedQueue(router, ['/']);
await Promise.all([
publish(),
Promise.delay(250).then(publish),
Promise.delay(300).then(() => this.proxy.interrupt(3000)),
Promise.delay(5000).then(publish),
]);
await Promise.all([
transport.closeAllConsumers(),
transport._queues.get(kReestablishConsumer).deleteAsync(),
]);
} finally {
transport.removeAllListeners('publish');
assert.equal(counter, 6); // 3 requests, 3 responses
for (const msg of args) {
assert.deepStrictEqual(msg, sample);
}
}
});
it('should create consumed queue', async () => {
const { transport } = this;
let done;
let fail;
const promise = new Promise((resolve, reject) => {
done = resolve;
fail = reject;
});
const kReestablishConsumer = await transport.createConsumedQueue(router);
const queue = transport._queues.get(kReestablishConsumer);
await transport.bindExchange(queue, '/');
// #1 trigger error
debug('called interrupt (1) in 20');
this.proxy.interrupt(20);
let attempt = 0;
transport.on('consumed-queue-reconnected', async () => {
attempt += 1;
assert.equal(attempt, 1, 'must only trigger once');
// #2 reconnected, try publish
try {
const message = await transport
.publishAndWait('/', { foo: 'bar' }, { timeout: 500 });
// #4 OK, try unbind
assert.deepEqual(message, { bar: 'baz' });
debug('unbind exchange from /', queue.queueOptions.name);
const activeQueue = transport._queues.get(kReestablishConsumer);
await transport.unbindExchange(activeQueue, '/');
// #5 unbound, let's reconnect
transport.removeAllListeners('consumed-queue-reconnected');
transport.on('consumed-queue-reconnected', async () => {
debug('reconnected for the second time, publish must not succeed');
// #7 reconnected again
// dont wait for actual publish, if message comes router
// will throw and crash the process
transport.publish('/', { bar: 'foo' });
// resolve only on second attempt after proxy interrupt
await Promise.delay(1000).then(done);
});
// #6 trigger error again
await Promise.delay(10);
debug('called interrupt (2) in 20');
this.proxy.interrupt(20);
} catch (e) {
debug('error for publish', e);
fail(e);
}
});
await promise;
});
});
describe('response headers', function test() {
const tracer = new MockTracer();
before('init transport', async () => {
this.proxy = new Proxy(9010, RABBITMQ_PORT, RABBITMQ_HOST);
this.transport = new AMQPTransport({
connection: {
port: 9010,
heartbeat: 2000,
},
debug: true,
exchange: 'test-direct',
exchangeArgs: {
autoDelete: false,
type: 'direct',
},
defaultQueueOpts: {
autoDelete: true,
exclusive: true,
},
tracer,
});
await this.transport.connect();
});
after('cleanup', async () => {
await this.transport.close();
await this.proxy.close();
});
function router(message, headers, raw, next) {
const error = new Error('Error occured but at least you still have your headers');
switch (headers.routingKey) {
case '/include-headers':
assert.deepEqual(message, { foo: 'bar' });
return next(null, { bar: 'baz' });
case '/return-custom-header':
assert.deepEqual(message, { foo: 'bar' });
raw.properties[kReplyHeaders] = { 'x-custom-header': 'custom-header-value' };
return next(null, { bar: 'baz' });
case '/return-headers-on-error':
assert.deepEqual(message, { foo: 'bar' });
raw.properties[kReplyHeaders] = { 'x-custom-header': 'error-but-i-dont-care' };
return next(error, null);
default:
throw new Error();
}
}
it('is able to return detailed response with headers', async () => {
const { transport } = this;
const sample = { foo: 'bar' };
let counter = 0;
const args = [];
transport.on('publish', (route, msg) => {
if (route === '/include-headers') {
args.push(msg);
counter += 1;
} else {
counter += 1;
}
});
try {
const kReestablishConsumer = await transport.createConsumedQueue(router, ['/include-headers']);
const response = await transport.publishAndWait('/include-headers', sample, {
confirm: true,
simpleResponse: false,
});
assert.deepEqual(
response,
{
data: { bar: 'baz' },
headers: { timeout: 10000 },
}
);
await Promise.all([
transport.closeAllConsumers(),
transport._queues.get(kReestablishConsumer).deleteAsync(),
]);
} finally {
transport.removeAllListeners('publish');
assert.equal(counter, 2); // 1 requests, 1 responses
for (const msg of args) {
assert.deepStrictEqual(msg, sample);
}
}
});
it('is able to set custom reply headers', async () => {
const { transport } = this;
const sample = { foo: 'bar' };
let counter = 0;
const args = [];
transport.on('publish', (route, msg) => {
if (route === '/return-custom-header') {
args.push(msg);
counter += 1;
} else {
counter += 1;
}
});
try {
const kReestablishConsumer = await transport.createConsumedQueue(router, ['/return-custom-header']);
const response = await transport.publishAndWait('/return-custom-header', sample, {
confirm: true,
simpleResponse: false,
});
assert.deepEqual(
response,
{
data: { bar: 'baz' },
headers: { 'x-custom-header': 'custom-header-value', timeout: 10000 },
}
);
await Promise.all([
transport.closeAllConsumers(),
transport._queues.get(kReestablishConsumer).deleteAsync(),
]);
} finally {
transport.removeAllListeners('publish');
assert.equal(counter, 2); // 1 requests, 1 responses
for (const msg of args) {
assert.deepStrictEqual(msg, sample);
}
}
});
it('is able to return headers with error response', async () => {
const { transport } = this;
const sample = { foo: 'bar' };
let counter = 0;
const args = [];
transport.on('publish', (route, msg) => {
if (route === '/return-headers-on-error') {
args.push(msg);
counter += 1;
} else {
counter += 1;
}
});
try {
const kReestablishConsumer = await transport.createConsumedQueue(router, ['/return-headers-on-error']);
try {
await transport.publishAndWait('/return-headers-on-error', sample, {
confirm: true,
simpleResponse: false,
});
} catch (error) {
// here I should expect headers
assert.strictEqual('Error occured but at least you still have your headers', error.message);
assert.deepEqual({ 'x-custom-header': 'error-but-i-dont-care', timeout: 10000 }, error[kReplyHeaders]);
await Promise.all([
transport.closeAllConsumers(),
transport._queues.get(kReestablishConsumer).deleteAsync(),
]);
}
} finally {
transport.removeAllListeners('publish');
assert.equal(counter, 2); // 1 requests, 1 responses
for (const msg of args) {
assert.deepStrictEqual(msg, sample);
}
}
});
});
});
<file_sep>const Errors = require('common-errors');
const generateErrorMessage = require('./error');
/**
* In-memory reply storage
*/
class ReplyStorage {
constructor(Type = Map) {
this.storage = new Type();
this.onTimeout = this.onTimeout.bind(this);
}
/**
* Invoked on Timeout Error
* @param {string} correlationId
* @returns {Void}
*/
onTimeout(correlationId) {
const { storage } = this;
const { reject, routing, timeout } = storage.get(correlationId);
// clean-up
storage.delete(correlationId);
// reject with a timeout error
setImmediate(reject, new Errors.TimeoutError(generateErrorMessage(routing, timeout)));
}
/**
* Stores correlation ID in the memory storage
* @param {string} correlationId
* @param {Object} opts - Container.
* @param {Function} opts.resolve - promise resolve action.
* @param {Function} opts.reject - promise reject action.
* @param {number} opts.timeout - expected response time.
* @param {string} opts.routing - routing key for error message.
* @param {boolean} [opts.simple] - whether return body-only response or include headers
* @param {Array[number]} opts.time - process.hrtime() results.
* @param {Record<string, any>} opts.replyOptions
* @param {NodeJS.Timer | null} [opts.timer]
* @param {any} [opts.cache]
* @returns {Void}
*/
push(correlationId, opts) {
opts.timer = setTimeout(this.onTimeout, opts.timeout, correlationId);
this.storage.set(correlationId, opts);
}
/**
* Rejects stored promise with an error & cleans up
* Timeout error
* @param {string} correlationId
* @param {Error} error
* @returns {void}
*/
reject(correlationId, error) {
const { storage } = this;
const { timer, reject } = storage.get(correlationId);
// remove timer
clearTimeout(timer);
// remove reference
storage.delete(correlationId);
// now resolve promise and return an error
setImmediate(reject, error);
}
pop(correlationId) {
const future = this.storage.get(correlationId);
// if undefind - early return
if (future === undefined) {
return undefined;
}
// cleanup timeout
clearTimeout(future.timer);
// remove reference to it
this.storage.delete(correlationId);
// return data
return future;
}
}
module.exports = ReplyStorage;
<file_sep>const omit = require('lodash/omit');
const { MSError } = require('./utils/serialization');
// error data that is going to be copied
const copyErrorData = [
'code', 'name', 'errors',
'field', 'reason', 'stack',
];
/**
* Wraps response error
* @param {Error | Record<string, any>} originalError
* @returns {Error}
*/
exports.wrapError = function wrapError(originalError) {
if (originalError instanceof Error) {
return originalError;
}
// this only happens in case of .toJSON on error object
const error = new MSError(originalError.message);
for (const fieldName of copyErrorData) {
const mixedData = originalError[fieldName];
if (mixedData !== undefined && mixedData !== null) {
error[fieldName] = mixedData;
}
}
return error;
};
/**
* Set queue opts
* @param {Object} opts
* @return {Object}
*/
exports.setQoS = function setQoS(opts) {
const { neck, noAck } = opts;
const output = omit(opts, ['neck', 'noAck']);
if (typeof neck === 'undefined') {
output.noAck = true;
} else {
output.noAck = noAck == null ? false : noAck;
output.prefetchCount = neck > 0 ? neck : 0;
}
return output;
};
<file_sep>const Joi = require('joi');
/**
* Settings confirm to [policy: string] : settings schema
* @constructor
* @param {Object} settings - Container for policies.
* @param {number} settings.min - Min delay for attempt.
* @param {number} settings.max - Max delay for attempt.
* @param {number} settings.factor - Exponential factor.
*/
class Backoff {
constructor(settings) {
this.settings = Object.setPrototypeOf({ ...settings }, null);
}
get(policy, attempt = 0) {
const { min, factor, max } = this.settings[policy];
if (attempt === 0) return 0;
if (attempt === 1) return min;
return Math.min(Math.round((Math.random() + 1) * min * (factor ** (attempt - 1))), max);
}
}
Backoff.schema = Joi.object({
private: Joi.object({
min: Joi.number().min(0)
.description('min delay for attempt #1')
.default(250),
max: Joi.number().min(0)
.description('max delay')
.default(1000),
factor: Joi.number().min(1)
.description('exponential increase factor')
.default(1.2),
}).default(),
consumed: Joi.object({
min: Joi.number().min(0)
.description('min delay for attempt #1')
.default(500),
max: Joi.number().min(0)
.description('max delay')
.default(5000),
factor: Joi.number().min(1)
.description('exponential increase factor')
.default(1.2),
}).default(),
});
module.exports = Backoff;
<file_sep>// quick noop-logger implementation
const noop = require('lodash/noop');
const logLevels = require('./index').levels;
const logger = Object.create(null);
const assignLevels = (prev, level) => {
prev[level] = noop;
return prev;
};
logLevels.reduce(assignLevels, logger);
module.exports = logger;
| cf735829ea842f7d138819362f81fcdba619695e | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | microfleet/transport-amqp | caeea5f4148c8592ba3cd415c15d7b27dc55dc24 | 40036c19331c4f7ad549512dc86f21ae873360c0 |
refs/heads/master | <file_sep>import java.math.BigInteger;
import java.util.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* This algorithm creates a random private key that can be used for creating
* cryptocurrency wallets. The final private key is in base58 (bitcoin).
*
* @author <NAME>
*/
public class PrivateKey {
public static void main(String args[]) {
String eightyString = "80" + HexaString(); // adding "80" to front of string
System.out.println("eightyString: " + eightyString);
String sha = "";
String doubleHash = "";
String endDigits = "";
try {
sha = sha256(eightyString); // first hash
System.out.println("first sha256: " + sha);
doubleHash = sha256(sha); // second hash
System.out.println("second sha256 (doubleHash): " + doubleHash);
} catch (NoSuchAlgorithmException e) {
}
for (int x = 0; x < 8; x++) // getting first 8 digits of double hash
{
String digits = String.valueOf(doubleHash.charAt(x));
endDigits += digits;
}
System.out.println("End digits: " + endDigits);
String baseConvert = eightyString + endDigits; // adding 8 digits to end of 80 string
System.out.println(baseConvert);
byte[] bytearraynumber = hexStringToByteArray(baseConvert);
BigInteger bignumber = new BigInteger(1, bytearraynumber);
System.out.println("converted to decimal: " + bignumber); // changed to decimal
BigInteger fiftyEight = new BigInteger("58");
BigInteger zero = new BigInteger("0");
BigInteger remainder = new BigInteger("0");
String reverseKey = " ";
String finalKey = " ";
while (bignumber.compareTo(zero) != 0) {
String alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // base 58
remainder = bignumber.mod(fiftyEight); // keeping remainder
bignumber = bignumber.divide(fiftyEight); // dividing bignumber
int position = remainder.intValue(); // remainder to int
String key = String.valueOf(alphabet.charAt(position)); // getting base 58 value
reverseKey += key; // adding to string (is the reverse of private key)
}
for (int x = reverseKey.length() - 1; x > 0; x--) // reversing reverseKey to private key
{
String add = String.valueOf(reverseKey.charAt(x));
finalKey += add;
}
System.out.println("Private Key: " + finalKey); // Private key
}
public static String HexaString() // creating a random hexadecimal string with 64 bits
{
String[] hexArray = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
Random randHexa = new Random();
String ecdsa = "";
for (int x = 0; x < 64; x++) {
int rnd = randHexa.nextInt(hexArray.length); // random num b/w 0 and 15
String arrayValue = hexArray[rnd]; // using rand num to get value in array
String addOn = arrayValue;
ecdsa += addOn; // concat string
}
System.out.println("ecdsa: " + ecdsa); // printing to see if works
return ecdsa;
}
static String sha256(String input) throws NoSuchAlgorithmException // hashing code
{
byte[] in = hexStringToByteArray(input);
MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
byte[] result = mDigest.digest(in);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static byte[] hexStringToByteArray(String s) // changing the Hexadecimal string to a Byte array
{
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}<file_sep># Algorithms
This repository contains alogrithms that I worked on during my Higher Diploma in Software Development.
Each file contains documentation about what the algorithm does. | 7b044b4c7fce558140ffd15a6ec74ee6e68d0271 | [
"Markdown",
"Java"
] | 2 | Java | HartSarah/Algorithms | a31a166f0bca8975bb26479d64f649309a69435e | d1d4e608b0c43bbe1f1995a0feaf957101de12b5 |
refs/heads/master | <file_sep>var url = 'http://test-blobupload-service.apps.javelinmc.com/api/blob/upload/file';
$(document).ready(function () {
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function () { };
console.log = function (message) {
console.olog(message);
$('#logs').append('<p>' + message + '</p>');
$('#logs').scrollTop($('#logs')[0].scrollHeight);
};
console.error = console.debug = console.info = console.log
window.allFiles = [];
var chooseFile = document.getElementById('fielss');
chooseFile.addEventListener('change', function (e) {
allFiles = [];
for (var i = 0; i < this.files.length; i++) {
var go = new uploadChunk(this.files[i]);
go.nextByte();
allFiles.push(go);
}
});
function checkAllFiles() {
var isAlldone = true;
for (var i = 0; i < allFiles.length; i++) {
if (!allFiles[i].isCompleted) {
isAlldone = false;
break;
}
}
if (isAlldone) {
alert("Finished done");
}
}
function uploadChunk(blob) {
var self = this;
this.BYTES_PER_CHUNK;
this.SIZE;
this.isCompleted = false;
this.NUM_CHUNKS
this.start;
this.end;
this.isFailed;
this.chunk;
this.BYTES_PER_CHUNK = 2097152;//1048576; 1mb
this.SIZE = blob.size;
this.NUM_CHUNKS = Math.max(Math.ceil(this.SIZE / this.BYTES_PER_CHUNK), 1);
this.start = 0;
this.chunk = 0;
this.end = this.BYTES_PER_CHUNK;
this.name = blob.name;
this.blob = blob;
this.isFailed = false;
this.failed = function () {
self.isFailed = true;
console.log("failed for chunk "+self.chunk + " of "+ self.name);
alert("failed chunk");
}
this.nextByte = function nextByte() {
if (self.start < self.SIZE) {
if (!self.isFailed) {
console.log("file <" + self.name + " > :: sending " + self.chunk + " out of " + self.NUM_CHUNKS);
upload(self.blob.slice(self.start, self.end), self.NUM_CHUNKS, self.name, self.chunk++, self.failed, self.nextByte);
self.start = self.end;
self.end = self.start + self.BYTES_PER_CHUNK;
} else {
alert(self.chunk + "failed");
}
} else {
console.log("Completed file < " + self.name + " >");
self.isCompleted = true;
checkAllFiles();
}
}
//nextByte(true, SIZE, start);
}
function upload(blobOrFile, chunks, name, chunk, failed, nextByte) {
var fd = new FormData();
fd.append("name", name);
fd.append('chunk', chunk);
fd.append('chunks', chunks);
fd.append('file', blobOrFile);
fd.append('time', new Date().getTime());
fd.append('user', "temp");
var xhr;
xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.upload.onprogress = function (e) {
var total = 0;
if (e.lengthComputable) {
total = Math.round((e.loaded / e.total) * 100);
//var totalOutOf = ((chunk + 1) * total) / chunks;
// console.log("% of " + name + "= " + totalOutOf);
}
if (total === 100) {
//nextCalled = true;
// nextByte(true);
}
};
xhr.onload = function () {
// check if upload made itself through
if (xhr.status >= 400) {
failed();
return;
}
console.log("file <" + name + " > :: done sending " + chunk + " out of "+chunks);
setTimeout(function () {
nextByte(true);
}, 1);
}
xhr.onloadend = function (e) {
xhr = null;
};
xhr.send(fd);
};
}); | bad07352f38c544f91ba55ba8848b6e55aecc5f1 | [
"JavaScript"
] | 1 | JavaScript | vijay22uk/chunk-upload | e55c2dc50ed3319100a4705d787686239a45457f | f5130b2791805b38021830b190bf037897a23928 |
refs/heads/master | <repo_name>c915384165/SQL_learning<file_sep>/mycsv/__init__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = ["csv_interface"]
import csv
def csv_interface(filename):
## 读取csv文件,返回一个列表,每行为一个子列表
ls = []
with open(filename,'r', newline='') as fo:
reader = csv.reader(fo, dialect='excel', delimiter=',')
for row in reader:
ls.append(row)
return ls
<file_sep>/README.md
# SQL_learning
学习SQL语法
<file_sep>/search.sql
-- 查询数据
-- 基本查询
-- 查询students表中所有数据
SELECT * FROM students;
-- 查询classes表中所有数据
SELECT * FROM classes;
-- 计算100+200
SELECT 100+200;
-- 条件查询
-- 按条件查询students
SELECT * FROM students WHERE score >= 80;
-- 按AND条件查询students
SELECT * FROM students WHERE score >= 80 AND gender = "M";
-- 按 OR 条件查询studetns
SELECT * FROM students WHERE score >= 80 OR gender = "M";
-- 按 NOT 条件查询students
SELECT * FROM students WHERE NOT class_id = 2;
SELECT * FROM students WHERE class_id <> 2;
-- 按多个条件查询students
SELECT * FROM students WHERE (score < 80 OR score > 90) AND gender = "M";
-- 按多个条件查询LIKE判断 %表示任意字符
SELECT * FROM students WHERE name LIKE "%ab%";
-- 查询分数在60-90分之间的学生
SELECT * FROM students WHERE score >= 60 AND score <= 90;
SELECT * FROM students WHERE score BETWEEN 60 AND 90;
-- 投影查询
-- SELECT 列1, 列2, 列3 FROM ...
SELECT id, score, name FROM students;
-- SELECT 列1 别名1, 列2 别名2, 列3 别名3 FROM
-- 使用投影查询,并将列名重命名:
SELECT id, score points, name FROM students;
-- 使用投影查询+WHERE条件:
SELECT id, score points, name FROM students WHERE gender = 'M';
-- 排序
-- 按score从低到高
SELECT id, name, gender, score FROM students ORDER BY score;
-- 按score从高到低
SELECT id, name, gender, score FROM students ORDER BY score DESC;
-- 继续排序
SELECT id, name, gender, score FROM students ORDER BY score DESC, gender;
-- 默认排序是ASC
-- ORDER BY score ASC = ORDER BY score
-- 带 WHERE 条件的 ORDER BY
SELECT id, name, gender, score
FROM students
WHERE class_id = 1
ORDER BY score DESC;
-- 分页查询
-- 查询第一页
SELECT id, name, gender, score
FROM students
-- WHERE
ORDER BY score DESC
LIMIT 3 OFFSET 0;
-- OFFSET 简写
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 3;
-- OFFSET 简写2
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 15 OFFSET 30;
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 30, 15;
-- 聚合查询
SELECT COUNT(*) FROM students;
-- 使用聚合查询
SELECT COUNT(*) boys FROM students WHERE gender = "M";
-- 聚合函数
-- SUM() AVG() MIN() MAX()
-- 使用聚合查询计算男生平均成绩
SELECT AVG(score) average FROM students WHERE gender = "M";
-- 分组
SELECT COUNT(*) FROM students GROUP BY class_id;
-- 按class_id 分组
SELECT class_id, COUNT(*) num FROM students GROUP BY class_id, gender;
-- 多表查询
SELECT * FROM students, classes;
-- set alias
SELECT
students.id sid,
students.name,
students.gender,
students.score,
classes.id cid,
classes.name cname
FROM students, classes;
-- 子表别名
SELECT
s.id sid,
s.name,
s.gender,
s.score,
c.id cid,
c.name cname
FROM students s, classes c;
-- 连接查询
-- 选出所有学生
SELECT s.id, s.name, s.class_id, s.gender, s.score FROM students s;
-- 选出所有学生,同时返回班级名称
SELECT
s.id,
s.name,
s.class_id,
s.gender,
s.score
FROM students s
INNER JOIN classes c
ON s.class_id = c.id;
-- INNER JOIN 写法
-- 1. 先确定主表,仍然使用FROM <表1>的语法;
-- 2. 再确定需要连接的表,使用INNER JOIN <表2>的语法;
-- 3. 然后确定连接条件,使用ON <条件...>,这里的条件是s.class_id = c.id,表示students表的class_id列与classes表的id列相同的行需要连接;
-- 4. 可选:加上WHERE子句、ORDER BY等子句。
-- 使用 OUTER JOIN
SELECT
s.id,
s.name,
s.class_id,
c.name class_name,
s.gender, s.score
FROM students s
RIGHT OUTER JOIN classes c
ON s.class_id = c.id;
-- 使用 LEFT OUTER JOIN
SELECT
s.id,
s.name,
s.class_id,
c.name class_name,
s.gender,
s.score
FROM students s
LEFT OUTER JOIN classes c
ON s.class_id = c.id;
-- 使用FULL OUTER JOIN
SELECT
s.id,
s.name,
s.class_id,
c.name class_name,
s.gender, s.score
FROM students s
FULL OUTER JOIN classes c
ON s.class_id = c.id;
<file_sep>/CRUD.sql
-- CRUD: Create, Retrieve, Update, Delete.
-- * INSERT: 插入新纪录
-- * UPDATE: 更新纪录
-- * DELETE: 删除记录
-- 添加一条新记录至students
INSERT INTO students (class_id, name, gender, score)
VALUES (2, '大牛', 'M', 80);
-- 添加多条记录至students
INSERT INTO students (class_id, name, gender, score)
VALUES
(1, '大宝', 'M', 87),
(2, '二宝', 'M', 81);
-- 更新表students,设置,name -> '大牛', score -> 66,定位id=1
UPDATE students SET name='大牛', score=66 WHERE id=1;
-- 查询并观察结果:
SELECT * FROM students WHERE id=1;
-- 更新id=5,6,7的记录
UPDATE students SET name='小牛', score=77 WHERE id>=5 AND id<=7;
-- 查询并观察结果:
SELECT * FROM students;
-- 更新score<80的记录
UPDATE students SET score=score+10 WHERE score<80;
-- 查询并观察结果:
SELECT * FROM students;
-- 删除id=1的记录
DELETE FROM students WHERE id=1;
-- 查询并观察结果:
SELECT * FROM students;
-- 删除id=5,6,7的记录
DELETE FROM students WHERE id>=5 AND id<=7;
-- 查询并观察结果:
SELECT * FROM students;
-- 直接替换:
REPLACE INTO students (id, class_id, name, gender, score)
VALUES (1, 1, '小明', 'F', 99);<file_sep>/w3school_SQL.md
# select
## 语法
SELECT 语句用于从表中选取数据。
结果被存储在一个结果表中(称为结果集)。
```SQL
SELECT 列名称 FROM 表名称;
SELECT * FROM 表名称;
```
## 实例
```
SELECT LastName,FirstName FROM Persons;
SELECT * FROM Persons;
```
# SELECT DISTINCT
在表中,可能会包含重复值。
这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。
关键词 DISTINCT 用于返回唯一不同的值。
## 语法
```
SELECT DISTINCT 列名称 FROM 表名称;
```
## 实例
```
SELECT DISTINCT Company FROM Orders;
```
# WHERE
如需有条件地从表中选取数据,可将 WHERE 子句添加到 SELECT 语句。
## 语法
```
SELECT 列名称 FROM 表名称 WHERE 列 运算符 值
```
## 实例
```sql
SELECT * FROM Persons WHERE City='Beijing'
-- 注意引号
SELECT * FROM Persons WHERE FirstName='Bush'
SELECT * FROM Persons WHERE Year>1965
```
# AND & OR
AND 和 OR 运算符用于基于一个以上的条件对记录进行过滤。
AND 和 OR 可在 WHERE 子语句中把两个或多个条件结合起来。
* 如果第一个条件和第二个条件都成立,则 AND 运算符显示一条记录。
* 如果第一个条件和第二个条件中只要有一个成立,则 OR 运算符显示一条记录。
## 语法
```
```
## 实例
```
SELECT * FROM Persons WHERE FirstName='Thomas' AND LastName='Carter'
SELECT * FROM Persons WHERE firstname='Thomas' OR lastname='Carter'
SELECT * FROM Persons WHERE (FirstName='Thomas' OR FirstName='William')
AND LastName='Carter'
```
# ORDER BY
## ORDER BY 语句
ORDER BY 语句用于根据指定的列对结果集进行排序。
ORDER BY 语句默认按照升序对记录进行排序。
如果您希望按照降序对记录进行排序,可以使用 `DESC` 关键字。
## 语法
```
```
## 实例
```
SELECT Company, OrderNumber FROM Orders ORDER BY Company
SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC
```
# INSERT INTO
INSERT INTO 语句用于向表格中插入新的行。
## 语法
```
INSERT INTO 表名称 VALUES (值1, 值2,....)
INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
```
## 实例
```
INSERT INTO Persons VALUES ('Gates', 'Bill', 'Xuanwumen 10', 'Beijing')
INSERT INTO Persons (LastName, Address) VALUES ('Wilson', 'Champs-Elysees')
```
# UPDATE
Update 语句用于修改表中的数据。
## 语法
```
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
```
## 实例
```
UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
UPDATE Person SET Address = 'Zhongshan 23', City = 'Nanjing'
WHERE LastName = 'Wilson'
```
# DELETE
DELETE 语句用于删除表中的行。
## 语法
```
DELETE FROM 表名称 WHERE 列名称 = 值
```
## 实例
```
-- 删除某行
DELETE FROM Person WHERE LastName = 'Wilson'
-- 删除所有行
DELETE FROM table_name
DELETE * FROM table_name
```
# LIMIT
TOP 子句用于规定要返回的记录的数目。
对于拥有数千条记录的大型表来说,TOP 子句是非常有用的。
注释:并非所有的数据库系统都支持 TOP 子句。
## 语法
```
SELECT column_name(s)
FROM table_name
LIMIT number
```
## 实例
```
SELECT *
FROM Persons
LIMIT 5
-- 查询第一页
SELECT id, name, gender, score
FROM students
-- WHERE
ORDER BY score DESC
LIMIT 3 OFFSET 0;
-- OFFSET 简写
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 3;
-- OFFSET 简写2
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 15 OFFSET 30;
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 30, 15;
```
# LIKE
LIKE 操作符用于在 WHERE 子句中搜索列中的指定模式。
## 语法
```
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
```
## 实例
```
SELECT * FROM Persons
WHERE City LIKE 'N%'
SELECT * FROM Persons
WHERE City LIKE '%g'
SELECT * FROM Persons
WHERE City LIKE '%lon%'
```
# 通配符
* %=替代一个或多个字符
* _=仅替代一个字符
* [charlist]=字符列中的任何单一字符
* [^charlist]或者[!charlist]=不在字符列中的任何单一字符
## 语法
```
```
## 实例
```
SELECT * FROM Persons
WHERE City LIKE 'Ne%'
SELECT * FROM Persons
WHERE City LIKE '%lond%'
SELECT * FROM Persons
WHERE FirstName LIKE '_eorge'
SELECT * FROM Persons
WHERE LastName LIKE 'C_r_er'
SELECT * FROM Persons
WHERE City LIKE '[ALN]%'
SELECT * FROM Persons
WHERE City LIKE '[!ALN]%'
```
# IN
IN 操作符允许我们在 WHERE 子句中规定多个值。
## 语法
```
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
```
## 实例
```
SELECT * FROM Persons
WHERE LastName IN ('Adams','Carter')
```
# BETWEEN
操作符 BETWEEN ... AND 会选取介于两个值之间的数据范围。这些值可以是数值、文本或者日期。
## 语法
```
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
```
## 实例
```
SELECT * FROM Persons
WHERE LastName
BETWEEN 'Adams' AND 'Carter'
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Adams' AND 'Carter'
```
# Alias
通过使用 SQL,可以为列名称和表名称指定别名(Alias)。
## 语法
```
SELECT column_name(s)
FROM table_name
AS alias_name
SELECT column_name AS alias_name
FROM table_name
```
## 实例
```
```
# JOIN
JOIN用于根据两个或多个表中的列之间的关系,从这些表中查询数据。
## Join 和 Key
有时为了得到完整的结果,我们需要从两个或更多的表中获取结果。我们就需要执行 join。
数据库中的表可通过键将彼此联系起来。主键(Primary Key)是一个列,在这个列中的每一行的值都是唯一的。在表中,每个主键的值都是唯一的。
这样做的目的是在不重复每个表中的所有数据的情况下,把表间的数据交叉捆绑在一起。
## 语法
```
```
## 实例
```
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons, Orders
WHERE Persons.Id_P = Orders.Id_P
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.Id_P = Orders.Id_P
ORDER BY Persons.LastName
```
# SQL UNION
UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
## 语法
```
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
```
> 注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。
UNION ALL 命令和 UNION 命令几乎是等效的,不过 UNION ALL 命令会列出所有的值。
## 实例
```
SELECT E_Name FROM Employees_China
UNION
SELECT E_Name FROM Employees_USA
SELECT E_Name FROM Employees_China
UNION ALL
SELECT E_Name FROM Employees_USA
```
#
## 语法
```
```
## 实例
```
```
#
## 语法
```
```
## 实例
```
```
#
## 语法
```
```
## 实例
```
```
#
## 语法
```
```
## 实例
```
```
<file_sep>/manager.sql
-- 管理数据库
-- DATABASES
-- 列出数据库;
SHOW DATABASES;
-- 切换数据库
USE test;
-- 创建数据库
CREATE DATABASE database_name;
-- 删除一个数据库
DROP DATABASE database_name;
-- 表
-- 列出表;
SHOW TABLES;
-- 查看表结构
DESC database_name;
-- 查看创建表的SQL语句
SHOW CREATE TABLE database_name;
-- 删除表
DROP TABLE database_name;
-- 修改表
-- 修改students表
-- 新增一列birth, 类型 -> VARCHAR(10) NOT NULL
ALTER TABLE students
ADD COLUMN birth VARCHAR(10) NOT NULL;
-- 修改students表
-- 列名 birth -> birthday,列数据类型 -> VARCHAR(20) NOT NULL
ALTER TABLE students
CHANGE COLUMN birth birthday VARCHAR(20) NOT NULL;
-- 修改students表
-- 删除列 -> birthday
ALTER TABLE students
DROP COLUMN birthday;
-- 插入或替换
-- todo
-- 如果我们希望插入一条新记录(INSERT),但如果记录已经存在,
-- 就先删除原记录,再插入新记录。
<file_sep>/init-person-data.sql
-- 如果 test 数据库不存在,就创建 test 数据库:
CREATE DATABASE IF NOT EXISTS test;
-- 切换到person数据库
USE test;
-- 删除classes表和students表(如果存在):
DROP TABLE IF EXISTS person;
-- 创建 person 表:
CREATE TABLE person (
id BIGINT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
Address VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 插入 person 记录:
INSERT INTO person(id, LastName, FirstName, Address, City)
VALUES
(1, "Adams", "John", "Oxford Street", "London"),
(2, "Bush", "George", "Fifth Avenue", "New York"),
(3, "Carter", "Thomas", "Changan Street", "Beijing");
-- OK:
SELECT 'ok' as 'result:';
<file_sep>/init-shanshan-data.sql
-- 如果 test 数据库不存在,就创建 test 数据库:
CREATE DATABASE IF NOT EXISTS shanshan;
-- 切换到person数据库
USE shanshan;
-- 删除classes表和students表(如果存在):
DROP TABLE IF EXISTS shanshan;
-- 创建 person 表:
CREATE TABLE shanshan (
`编号` BIGINT NOT NULL AUTO_INCREMENT,
`发现单位` VARCHAR(100) NOT NULL DEFAULT '',
`日期` DATE,
`孕妇名字` VARCHAR(100) NOT NULL,
`丈夫名字` VARCHAR(100) DEFAULT '',
`地址` VARCHAR(200) DEFAULT '',
`电话` VARCHAR(50) DEFAULT '',
`高危因素` VARCHAR(100) DEFAULT '',
`风险等级` VARCHAR(10) DEFAULT '',
`分娩日期` DATE,
`分娩方式` VARCHAR(100) DEFAULT '',
`分娩地点` VARCHAR(100) DEFAULT '',
`分娩孕周` INT(100) DEFAULT 0,
`风险颜色2` VARCHAR(100) DEFAULT '',
PRIMARY KEY (`编号`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 插入 person 记录:
-- INSERT INTO `采购` (id, LastName, FirstName, Address, City)
-- VALUES
-- (1, "Adams", "John", "Oxford Street", "London"),
-- (2, "Bush", "George", "Fifth Avenue", "New York"),
-- (3, "Carter", "Thomas", "Changan Street", "Beijing");
-- OK:
SELECT 'ok' as 'result:';
| a6c0880ccf923191daaea2fa1185a4d1f2b4383a | [
"Markdown",
"SQL",
"Python"
] | 8 | Python | c915384165/SQL_learning | 496fd4653af68ad26e70ca55ea3f5d4aee378171 | 2fcc70a0a504d0bb9163c8b2f2133909503b5337 |
refs/heads/master | <file_sep>#等频分箱#
#处理列:fin_debit_pct_all_0m_1m #
select created_new,factor,count(*)
from (
select jg.created_new
,jg.account
,jg.fin_debit_pct_all_0m_1m
,case when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_00 and fin_debit_pct_all_0m_1m < pct_01 then concat('0.[',cast(pct_00 as int),',',cast(pct_01 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_01 and fin_debit_pct_all_0m_1m < pct_02 then concat('1.[',cast(pct_01 as int),',',cast(pct_02 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_02 and fin_debit_pct_all_0m_1m < pct_03 then concat('2.[',cast(pct_02 as int),',',cast(pct_03 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_03 and fin_debit_pct_all_0m_1m < pct_04 then concat('3.[',cast(pct_03 as int),',',cast(pct_04 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_04 and fin_debit_pct_all_0m_1m < pct_05 then concat('4.[',cast(pct_04 as int),',',cast(pct_05 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_05 and fin_debit_pct_all_0m_1m < pct_06 then concat('5.[',cast(pct_05 as int),',',cast(pct_06 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_06 and fin_debit_pct_all_0m_1m < pct_07 then concat('6.[',cast(pct_06 as int),',',cast(pct_07 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_07 and fin_debit_pct_all_0m_1m < pct_08 then concat('7.[',cast(pct_07 as int),',',cast(pct_08 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_08 and fin_debit_pct_all_0m_1m < pct_09 then concat('8.[',cast(pct_08 as int),',',cast(pct_09 as int),')')
when cnt > 10 and pct_10 > 1.0 and fin_debit_pct_all_0m_1m >= pct_09 and fin_debit_pct_all_0m_1m <= pct_10 then concat('9.[',cast(pct_09 as int),',',cast(pct_10 as int),']')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_00 and fin_debit_pct_all_0m_1m < pct_01 then concat('0.[',cast(round(pct_00,2) as string),',',cast(round(pct_01,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_01 and fin_debit_pct_all_0m_1m < pct_02 then concat('1.[',cast(round(pct_01,2) as string),',',cast(round(pct_02,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_02 and fin_debit_pct_all_0m_1m < pct_03 then concat('2.[',cast(round(pct_02,2) as string),',',cast(round(pct_03,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_03 and fin_debit_pct_all_0m_1m < pct_04 then concat('3.[',cast(round(pct_03,2) as string),',',cast(round(pct_04,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_04 and fin_debit_pct_all_0m_1m < pct_05 then concat('4.[',cast(round(pct_04,2) as string),',',cast(round(pct_05,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_05 and fin_debit_pct_all_0m_1m < pct_06 then concat('5.[',cast(round(pct_05,2) as string),',',cast(round(pct_06,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_06 and fin_debit_pct_all_0m_1m < pct_07 then concat('6.[',cast(round(pct_06,2) as string),',',cast(round(pct_07,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_07 and fin_debit_pct_all_0m_1m < pct_08 then concat('7.[',cast(round(pct_07,2) as string),',',cast(round(pct_08,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_08 and fin_debit_pct_all_0m_1m < pct_09 then concat('8.[',cast(round(pct_08,2) as string),',',cast(round(pct_09,2) as string),')')
when cnt > 10 and pct_10 <= 1.0 and fin_debit_pct_all_0m_1m >= pct_09 and fin_debit_pct_all_0m_1m <= pct_10 then concat('9.[',cast(round(pct_09,2) as string),',',cast(round(pct_10,2) as string),']')
else fin_debit_pct_all_0m_1m
end as factor
,a.*
from jxq_jg_json_new jg
left join (
select count(distinct fin_debit_pct_all_0m_1m) as cnt
,percentile(fin_debit_pct_all_0m_1m * 100,0.0)/100 as pct_00
,percentile(fin_debit_pct_all_0m_1m * 100,0.1)/100 as pct_01
,percentile(fin_debit_pct_all_0m_1m * 100,0.2)/100 as pct_02
,percentile(fin_debit_pct_all_0m_1m * 100,0.3)/100 as pct_03
,percentile(fin_debit_pct_all_0m_1m * 100,0.4)/100 as pct_04
,percentile(fin_debit_pct_all_0m_1m * 100,0.5)/100 as pct_05
,percentile(fin_debit_pct_all_0m_1m * 100,0.6)/100 as pct_06
,percentile(fin_debit_pct_all_0m_1m * 100,0.7)/100 as pct_07
,percentile(fin_debit_pct_all_0m_1m * 100,0.8)/100 as pct_08
,percentile(fin_debit_pct_all_0m_1m * 100,0.9)/100 as pct_09
,percentile(fin_debit_pct_all_0m_1m * 100,1.0)/100 as pct_10
from jxq_jg_json_new
where fin_debit_pct_all_0m_1m is not null
)a on 1 = 1
where jg.fin_debit_pct_all_0m_1m is not null
)aa
group by created_new,factor
order by created_new,factor
limit 999;<file_sep>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
data = pd.read_csv("D:\\modeling\\new_modeling_tool\\data\\td_score.csv")
data=data[data['y_flag']!=2]
col_l=list(data.columns)
# ,'age','certi_city','certi_province','register_channel_name'
# data['register_channel_name']='name_'+data['register_channel_name']
data=data[col_l]
data['y_flag']=data['y_flag'].apply(lambda x:'bad' if x==1 else 'good')
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
for col in data.columns:
data[col] = labelencoder.fit_transform(data[col])
y = data['y_flag']
print(y)
X = data.drop('y_flag', axis=1)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, train_size=0.8)
columns = X_train.columns
# from sklearn.preprocessing import StandardScaler
# ss_X = StandardScaler()
# ss_y = StandardScaler()
# X_train = ss_X.fit_transform(X_train)
# X_test = ss_X.transform(X_test)
from sklearn.tree import DecisionTreeClassifier
model_tree = DecisionTreeClassifier()
model_tree.fit(X_train, y_train)
y_prob = model_tree.predict_proba(X_test)[:,1]
y_pred = np.where(y_prob > 0.5, 1, 0)
model_tree.score(X_test, y_pred)
# 可视化树图
# data_ = pd.read_csv("mushrooms.csv")
data_feature_name =data.columns[1:]
data['y_flag']=data['y_flag'].apply(lambda x:'bad' if x==1 else 'good')
data_target_name = np.unique(data["y_flag"])
print(data_target_name)
import graphviz
import pydotplus
from sklearn import tree
from IPython.display import Image
import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/'
dot_tree = tree.export_graphviz(model_tree,out_file=None,feature_names=data_feature_name,class_names=data_target_name,filled=True, rounded=True,special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_tree)
img = Image(graph.create_png())
graph.write_png("out.png")<file_sep>from sklearn.exceptions import NotFittedError
import pandas as pd
import numpy as np
from collections import defaultdict
from typing import Dict, Iterable, Tuple, List
from pandas.api.types import is_numeric_dtype
from utils import force_zero_one, make_series, searchsorted
from binning.base import Binning
from binning.unsupervised import equal_frequency_binning
class ChiSquareBinning(Binning):
def __init__(self,
max_bin: int,
cols: list = None,
bins: dict = None,
categorical_cols: List[str] = None,
bin_cat_cols: bool = True,
encode: bool = True,
fill: int = -1,
force_monotonic: bool = True,
force_mix_label: bool = True,
strict: bool = True,
ignore_na: bool = True,
prebin: int = 100):
"""
:param max_bin: The number of bins to split into
:param cols: A list of columns to perform binning, if set to None, perform binning on all columns.
:param bins: A dictionary mapping column name to cutoff points
:param categorical_cols: A list of categorical columns
:param bin_cat_cols: Whether to perform binning on categorical columns
:param encode: If set to False, the result of transform will be right cutoff point of the interval
:param fill: Value used for inputing missing value
:param force_monotonic: Whether to force the bins to be monotonic with the
positive proportion of the label
:param force_mix_label: Whether to force all the bins to have mix labels
:param strict: If set to True, equal values will not be treated as monotonic
:param ignore_na: The monotonicity check will ignore missing value
:param prebin: An integer, number of bins to split into before the chimerge process.
Usage:
--------------
# >>> from sklearn.datasets import load_iris
# >>> from sklearn.linear_model import LogisticRegression
# >>> X, y = load_iris(return_X_y=True)
# >>> CB = ChiSquareBinning(max_bin=5, force_monotonic=True, force_mix_label=True)
# >>> encoded = CB.fit_transform(X, y)
# >>> CB.bins # get the cutoff points
"""
super().__init__(cols, bins, encode, fill)
self.max_bin = max_bin
self.categorical_cols = categorical_cols or []
self.bin_cat_cols = bin_cat_cols
self.force_monotonic = force_monotonic
self.force_mix_label = force_mix_label
self.strict = strict
self.ignore_na = ignore_na
# mapping for discrete variables
self.discrete_encoding = dict()
self.prebin = prebin
self._chisquare_cache = dict()
def calculate_chisquare(self, mapping: Dict[int, list], candidates: Iterable) -> float:
# try to get from the cache first
unique_x = frozenset(candidates)
if self._chisquare_cache.get(unique_x, False):
return self._chisquare_cache[unique_x]
count = {k: len(v) for k, v in mapping.items()}
actual_pos = {k: sum(v) for k, v in mapping.items()}
actual_neg = {k: (count[k] - actual_pos[k]) for k in candidates}
expected_ratio = self.expected_ratio
expected_pos = {k: v * expected_ratio for k, v in count.items()}
expected_neg = {k: (count[k] - expected_pos[k]) for k in candidates}
chi2 = sum((actual_pos[k] - expected_pos[k])**2 / expected_pos[k] + \
(actual_neg[k] - expected_neg[k])**2 / expected_neg[k]
for k in candidates)
dgfd = len(candidates) - 1
chi2 = chi2 / dgfd
self._chisquare_cache[unique_x] = chi2
return chi2
@staticmethod
def sorted_two_gram(X):
""" Two gram with the left element smaller than the right element in each pair
eg. sorted_two_gram([1, 3, 2]) -> [(1, 2), (2, 3)]
"""
unique_values = sorted(X)
return [(unique_values[i], unique_values[i + 1])
for i in range(len(unique_values) - 1)]
@staticmethod
def is_monotonic(i, strict=True, ignore_na=True) -> bool:
""" Check if an iterable is monotonic """
i = make_series(i)
diff = i.diff()[1:]
if ignore_na:
diff = diff[diff.notnull()]
sign = diff > 0 if strict else diff >= 0
if sign.sum() == 0 or (~sign).sum() == 0:
return True
return False
@staticmethod
def find_candidate(values: Iterable, target: int) -> list:
""" Return a list of candidatate values that's next bigger or next smaller than the target value.
The candidate list will have only one element when the target is the min or max in X.
ex. find_candidate([1, 2, 3, 0], 2) => [1, 3]
"""
values = sorted(values)
idx = values.index(target)
cnt = len(values)
return [values[i] for i in [idx - 1, idx + 1] if 0 <= i < cnt]
def encode_with_label(self, X: pd.Series, y: pd.Series) -> pd.Series:
""" Encode categorical features with its percentage of positive samples"""
X, y = make_series(X), make_series(y)
pct_pos = y.groupby(X).mean()
# save the mapping for transform()
self.discrete_encoding[X.name] = pct_pos
return X.map(pct_pos)
def is_monotonic_post_bin(self, mapping: Dict[int, list]):
""" Check whether the proportion of positive label is monotonic to bin value"""
pct_pos = sorted([(k, np.mean(v)) for k, v in mapping.items()])
return self.is_monotonic([i[1] for i in pct_pos], self.strict, self.ignore_na)
def merge_bin(self, mapping: Dict[int, list], replace_value, original_value) -> Dict[int, list]:
""" Replace the smaller value with the bigger one except when the replace value is the
minimum of X, that case we replace the bigger value with the the smaller one.
"""
def _replace(mapping: Dict[int, list], to_replace: int, value: int):
mapping[value].extend(mapping[to_replace])
del mapping[to_replace]
return mapping
# make sure replace_value is the bigger one
if replace_value < original_value:
replace_value, original_value = original_value, replace_value
if original_value == min(mapping):
return _replace(mapping, replace_value, original_value)
else:
return _replace(mapping, original_value, replace_value)
def merge_chisquare(self, mapping: Dict[int, list], candidates=None) -> Dict[int, list]:
""" Performs a single merge based on chi square value
returns a new X' with new groups
:param candidates: the candidate values that are allowed to merge, default set to all the values
"""
candidates = candidates or mapping.keys()
candidate_pairs = self.sorted_two_gram(candidates)
# find the pair with minimum chisquare in one-pass
min_idx, min_chi2 = 0, np.inf
for i, pair in enumerate(candidate_pairs):
chi2 = self.calculate_chisquare(mapping, pair)
if chi2 < min_chi2:
min_idx, min_chi2 = i, chi2
# replace the smaller value with the bigger one except for the minimum pair
small, large = candidate_pairs[min_idx]
return self.merge_bin(mapping, small, large)
def merge_purity(self, mapping: Dict[int, list]) -> Tuple[Dict[int, list], bool]:
""" Performs a single merge trying to merge bins with only 0 or a label into the adjacent mixed label bin
Return the updated mapping and a purity label
"""
# convert to list so we don't get error modifying dictionary during loop
for k in sorted(list(mapping.keys())):
pct_pos = np.mean(mapping[k])
if pct_pos * (1 - pct_pos) == 0:
merge_candidates = self.find_candidate(mapping.keys(), k)
# it merges to the candidate that has mix labels, if both candidates do, then
# it will merge to the larger value, if neither does, if will merge both candidates
if len(merge_candidates) == 1:
return self.merge_bin(mapping, merge_candidates[0], k), False
else:
left_cand, right_cand = merge_candidates
pct_pos_left = np.mean(mapping[left_cand])
pct_pos_right = np.mean(mapping[right_cand])
can_merge_left = 0 < (pct_pos_left + pct_pos) / 2 < 1
can_merge_right = 0 < (pct_pos_right + pct_pos) / 2 < 1
if can_merge_left and can_merge_right:
return self.merge_chisquare(mapping, [left_cand, k, right_cand]), False
elif can_merge_left:
return self.merge_bin(mapping, left_cand, k), False
elif can_merge_right:
return self.merge_bin(mapping, right_cand, k), False
else:
mapping = self.merge_bin(mapping, left_cand, k)
return self.merge_bin(mapping, right_cand, k), False
else:
return mapping, True
def _fit(self, X, y, **fit_parmas):
""" Fit a single feature and return the cutoff points"""
if not is_numeric_dtype(X) and X.name not in self.categorical_cols:
raise ValueError('Column {} is not numeric and not in categorical_cols.'.format(X.name))
y = force_zero_one(y)
X, y = make_series(X), make_series(y)
# if X is discrete, encode with positive ratio in y
if X.name in self.categorical_cols:
# the categorical columns will remain unchanged if
# we turn off bin_cat_cols
if not self.bin_cat_cols:
return None
X = self.encode_with_label(X, y)
# the number of bins is the number of cutoff points minus 1
n_bins = X.nunique() - 1
# if the number of bins is already smaller than `n_bins`
# then we'll leave this column as it is
if n_bins < self.max_bin:
return None
# speed up the process with prebinning
if self.prebin and n_bins > self.prebin:
X, _ = equal_frequency_binning(X, n=self.prebin, encode=False)
# X = make_series(X)
# convert to mapping
mapping = y.groupby(X).apply(list).to_dict()
# set the overall expected ratio
if len(mapping) == 0:
return [-np.inf]
self.expected_ratio = sum(sum(v) for v in mapping.values()) / sum(len(v) for v in mapping.values())
# if the expected_ratio is 0 or 1 there should be only 1 group and
# any not-null value will be encoded into 1
if self.expected_ratio == 0 or self.expected_ratio == 1:
return [-np.inf]
n_bins = len(mapping) - 1
# merge bins based on chi square
while n_bins > self.max_bin:
mapping = self.merge_chisquare(mapping)
n_bins = len(mapping) - 1
# merge bins to create mixed label in every bin
if self.force_mix_label and n_bins > 1:
is_pure = False
while not is_pure:
mapping, is_pure = self.merge_purity(mapping)
# merge bins to keep bins to be monotonic
if self.force_monotonic:
while len(mapping) - 1 > 2 and not self.is_monotonic_post_bin(mapping):
mapping = self.merge_chisquare(mapping)
# clean up the cache
self._chisquare_cache = dict()
return mapping.keys()
def _transform(self, X: pd.Series, y=None):
""" Transform a single feature"""
# map discrete value to its corresponding percentage of positive samples
col_name = X.name
if col_name in self.discrete_encoding:
# if the a new category is encountered, leave it as missing
X = X.map(self.discrete_encoding[col_name])
return super()._transform(X, y)
def get_interval_mapping(self, col_name: str):
""" Get the mapping from encoded value to its corresponding group. """
if self.bins is None:
raise NotFittedError('This {} is not fitted. Call the fit method first.'.format(self.__class__.__name__))
if col_name in self.discrete_encoding and isinstance(self.bins[col_name], list):
# categorical columns
encoding = self.discrete_encoding[col_name]
group = defaultdict(list)
for i, v in zip(searchsorted(self.bins[col_name], encoding), encoding.index):
group[i].append(v)
group = {k: ', '.join(map(str, v)) for k, v in group.items()}
group[0] = 'UNSEEN'
return group
else:
return super().get_interval_mapping(col_name)
if __name__ == '__main__':
import random
import pickle
import time
X = [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 6, 6, 6, 7, 7, 7, 7, 7]
y = [0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0]
X = pd.DataFrame({'a': X, 'b': X, 'c': X})
X = pd.DataFrame({'a': [random.randint(1, 20) for _ in range(1000)],
'b': [random.randint(1, 20) for _ in range(1000)],
'c': [random.randint(1, 20) for _ in range(1000)]})
y = [int(random.random() > 0.5) for _ in range(1000)]
CB = ChiSquareBinning(max_bin=5, categorical_cols=['a'], force_mix_label=False, force_monotonic=False,
prebin=100, encode=True, strict=False)
start = time.time()
CB.fit(X, y)
# print(CB.fit(X, y))
# print(time.time() - start)
# print(CB.transform(X))
print(CB.bins)
# print(pd.concat([X, CB.transform(X)], axis=1))
<file_sep>""" Implements the equal width and equal frequency binning """
import pandas as pd
import numpy as np
import warnings
from pandas.api.types import is_numeric_dtype
from utils import searchsorted, wrap_with_inf, assign_group, make_series
from .base import Binning
class EqualWidthBinning(Binning):
def __init__(self,
n: int,
cols: list = None,
bins: dict = None,
encode: bool = True,
fill: int = -1):
"""
:param n: Number of bins to split into
:param cols: A list of columns to perform binning, if set to None, perform binning on all columns.
:param bins: A dictionary mapping column name to cutoff points
:param encode: If set to False, the result of transform will be right cutoff point of the interval
If the input has missing values, it will be put under a seperate group with the largest bin value
:param fill: Used to fill in missing value.
"""
super().__init__(cols, bins, encode, fill)
self.n = n
def _fit(self, X: pd.Series, y=None, **fit_parmas):
""" Fit a single feature and return the cutoff points"""
if not is_numeric_dtype(X):
return None
def find_nearest_element(series, elem):
min_idx = (series - elem).abs().values.argmin()
return series.iloc[min_idx]
X_ = X[X.notnull()]
v_min, v_max = X_.min(), X_.max()
bins = [find_nearest_element(X_, elem) for elem in np.linspace(v_min, v_max, self.n+1)]
return bins
class EqualFrequencyBinning(Binning):
def __init__(self,
n: int,
cols: list = None,
bins: dict = None,
encode: bool = True,
fill: int = -1):
"""
:param q: Number of equal width intervals to split into
:param cols: A list of columns to perform binning, if set to None, perform binning on all columns.
:param bins: A series of cutoff points, if provided, n will be ignored
:param encode: If set to False, the result of transform will be right cutoff point of the interval
:param fill: Used to fill in missing value.
"""
super().__init__(cols, bins, encode, fill)
self.n = n
def _fit(self, X: pd.Series, y=None, **fit_parmas):
""" Fit a single feature and return the cutoff points"""
if not is_numeric_dtype(X):
return None
quantiles = np.linspace(0, len(X[X.notnull()]) - 1, self.n+1, dtype=int)
cutoff = X.sort_values().reset_index(drop=True)[quantiles]
# there might be duplicated cutoff points
return set(cutoff)
def equal_width_binning(X: pd.Series, n: int, encode: bool = True, fill: int = -1):
""" Shortcut for equal width binning on a Pandas.Series, returns
the encoded series and the cutoff points
"""
s_name = X.name or 0
EWB = EqualWidthBinning(n, encode=encode, fill=fill)
binned = EWB.fit_transform(X.to_frame())
return binned[s_name], EWB.bins[s_name]
def equal_frequency_binning(X: pd.Series, n: int, encode: bool = True, fill: int = -1):
""" Shortcut for equal frequency binning on a Pandas.Series, returns
the encoded series and the cutoff points
"""
s_name = X.name or 0
EFB = EqualFrequencyBinning(n, encode=encode, fill=fill)
binned = EFB.fit_transform(X.to_frame())
return binned[s_name], EFB.bins[s_name]
if __name__ == '__main__':
# s = pd.Series(list(range(20)) + [np.nan] * 4)
# EWB = EqualWidthBinning(n=5, encode=True)
# EFB = EqualFrequencyBinning(n=5, encode=False)
# print(EFB.fit_transform(s))
# print(EFB.bins)
# print(EFB.transform(s))
pass
<file_sep># -*- coding: utf-8 -*-
# import sqlalchemy as sql
import pandas as pd
import numpy as np
import xlsxwriter as xw
import xlrd as xl
import sys
import os
import datetime
def draw_woe(info,var_list,save_path):
today = datetime.date.today().strftime('%Y%m%d')
workbook = xw.Workbook("{1}_vars_woe_{0}.xlsx".format(today,save_path))
sheet_w = workbook.add_worksheet('Detail')
Title_fmt = workbook.add_format(
{'font_name': 'Segoe UI', 'font_color': 'white', 'font_size': 11, 'bold': True, 'pattern': 1,
'bg_color': '#0f243e', 'border': 1, 'border_color': 'white'})
title_fmt = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 11,
'bold': True,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'border_color': 'black'})
data_fmt = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 9,
'bold': False,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'align':'center',
'border_color': 'black',
'num_format': '0.00'})
data_fmt2 = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 9,
'bold': False,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'align':'center',
'border_color': 'black',
'num_format': '0.00%'})
curr_row = 0
for var_names in var_list:
print (var_names)
if var_names in info['var_name'].tolist():
data=info[info['var_name']==var_names]
var_name=data.columns[0]
tmp = data[[var_name,'Total_Num','Bad_Num','Good_Num','Total_Pcnt','Bad_Rate','Woe','IV','KS']]
tmp=tmp.fillna(0)
columns=[var_names,'Total_Num','Bad_Num','Good_Num','Total_Pcnt','Bad_Rate','Woe','IV','KS']
tmp_o=tmp[tmp[var_name]!='(-1.0,-1.0)'].reset_index(drop=True)
tmp_1=None
# write to the xlsx
sheet_w.write_string(curr_row, 0, var_names, Title_fmt)
curr_row += 1
# print columns
for col in range(len(columns)):
sheet_w.write_string(curr_row, col, columns[col], title_fmt)
if '(-1.0,-1.0)' in tmp[var_name].tolist():
tmp_1 = tmp[tmp[var_name] == '(-1.0,-1.0)'].reset_index(drop=True).iloc[0].tolist()
curr_row += 1
for col in range(len(columns)):
if col==0:
sheet_w.write_string(curr_row, col, str(tmp_1[col]), data_fmt)
else:
sheet_w.write_number(curr_row, col, tmp_1[col], data_fmt)
curr_row += 1
first_row = curr_row + 1
for row in range(tmp_o.shape[0]):
#var_name default index = 0
sheet_w.write_string(curr_row, 0, tmp_o[var_name][row], data_fmt)
sheet_w.write_number(curr_row, 1, tmp_o['Total_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 2, tmp_o['Bad_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 3, tmp_o['Good_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 4, tmp_o['Total_Pcnt'][row], data_fmt2)
sheet_w.write_number(curr_row, 5, tmp_o['Bad_Rate'][row], data_fmt2)
sheet_w.write_number(curr_row, 6, tmp_o['Woe'][row], data_fmt)
sheet_w.write_number(curr_row, 7, tmp_o['IV'][row], data_fmt)
sheet_w.write_number(curr_row, 8, tmp_o['KS'][row], data_fmt2)
curr_row+=1
end_row = curr_row
chart = workbook.add_chart({'type': 'bar'})
chart.set_size({'height': 200, 'width': 600})
if tmp_1:
begin_row=first_row-1
else:
begin_row=first_row
chart.add_series({
'values': '={2}!$G${0}:$G${1}'.format(begin_row, end_row, 'Detail'),
'categories':'={2}!$A${0}:$A${1}'.format(begin_row, end_row, 'Detail'),
# 'data_labels': {'value': True, 'position': 'outside_end'},
'name': '',
'trendline':{
'type':'polynomial',
'order':3,
'name':'trend'
}
})
chart.set_x_axis({'name':var_names+'_woe'})
chart.set_y_axis({'name':'bin'})
chart.set_style(1)
# chart.set_chartarea({'fill':{
# 'color':'blue',
# 'transpatency':70
# }})
sheet_w.insert_chart(first_row-3, 11, chart)
curr_row += 4
workbook.close()
# draw_woe(info,train_cols,'TD')
def draw_woe_fromdic(data_dic,save_path):
today = datetime.date.today().strftime('%Y%m%d')
workbook = xw.Workbook("{1}_vars_woe_{0}.xlsx".format(today,save_path))
sheet_w = workbook.add_worksheet('Detail')
Title_fmt = workbook.add_format(
{'font_name': 'Segoe UI', 'font_color': 'white', 'font_size': 11, 'bold': True, 'pattern': 1,
'bg_color': '#0f243e', 'border': 1, 'border_color': 'white'})
title_fmt = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 11,
'bold': True,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'border_color': 'black'})
data_fmt = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 9,
'bold': False,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'align':'center',
'border_color': 'black',
'num_format': '0.00'})
data_fmt2 = workbook.add_format(
{'font_name': 'Segoe UI',
'font_color': 'black',
'font_size': 9,
'bold': False,
'pattern': 1,
'bg_color': '#cccccc',
'border': 1,
'align':'center',
'border_color': 'black',
'num_format': '0.00%'})
curr_row = 0
for var_name,data in data_dic.items():
# print (var_name)
if data.shape[0]>0:
try:
# data=data.reset_index()
tmp = data[[var_name,'Total_Num','Bad_Num','Good_Num','Total_Pcnt','Bad_Rate','Woe','IV','KS']]
tmp=tmp.fillna(0)
columns=[var_name,'Total_Num','Bad_Num','Good_Num','Total_Pcnt','Bad_Rate','Woe','IV','KS']
tmp_o=tmp[tmp[var_name]!='(-1.0,-1.0)'].reset_index(drop=True)
tmp_1=None
# write to the xlsx
sheet_w.write_string(curr_row, 0, var_name, Title_fmt)
curr_row += 1
# print columns
for col in range(len(columns)):
sheet_w.write_string(curr_row, col, columns[col], title_fmt)
if '(-1.0,-1.0)' in tmp[var_name].tolist():
tmp_1 = tmp[tmp[var_name] == '(-1.0,-1.0)'].reset_index(drop=True).iloc[0].tolist()
curr_row += 1
for col in range(len(columns)):
if col==0:
sheet_w.write_string(curr_row, col, str(tmp_1[col]), data_fmt)
else:
sheet_w.write_number(curr_row, col, tmp_1[col], data_fmt)
curr_row += 1
first_row = curr_row + 1
for row in range(tmp_o.shape[0]):
#var_name default index = 0
sheet_w.write_string(curr_row, 0, tmp_o[var_name][row], data_fmt)
sheet_w.write_number(curr_row, 1, tmp_o['Total_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 2, tmp_o['Bad_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 3, tmp_o['Good_Num'][row], data_fmt)
sheet_w.write_number(curr_row, 4, tmp_o['Total_Pcnt'][row], data_fmt2)
sheet_w.write_number(curr_row, 5, tmp_o['Bad_Rate'][row], data_fmt2)
sheet_w.write_number(curr_row, 6, tmp_o['Woe'][row], data_fmt)
sheet_w.write_number(curr_row, 7, tmp_o['IV'][row], data_fmt)
sheet_w.write_number(curr_row, 8, tmp_o['KS'][row], data_fmt2)
curr_row+=1
end_row = curr_row
chart = workbook.add_chart({'type': 'bar'})
chart.set_size({'height': 200, 'width': 600})
if tmp_1:
begin_row=first_row-1
else:
begin_row=first_row
chart.add_series({
'values': '={2}!$G${0}:$G${1}'.format(begin_row, end_row, 'Detail'),
'categories':'={2}!$A${0}:$A${1}'.format(begin_row, end_row, 'Detail'),
# 'data_labels': {'value': True, 'position': 'outside_end'},
'name': '',
'trendline':{
'type':'polynomial',
'order':3,
'name':'trend'
}
})
chart.set_x_axis({'name':var_name+'_woe'})
chart.set_y_axis({'name':'bin'})
chart.set_style(1)
# chart.set_chartarea({'fill':{
# 'color':'blue',
# 'transpatency':70
# }})
sheet_w.insert_chart(first_row-3, 11, chart)
curr_row += 4
except:
print (var_name)
print(data)
workbook.close()<file_sep># -*- coding:utf-8 -*-
import tool
import pandas as pd
import numpy as np
import d00_param
import imp
import copy
imp.reload(d00_param)
import time
from collections import Counter
def combine(l, n):
'''
:param l:需组合所有变量list
:param n:组合变量数,两两、三三...
:return:所有新组合的变量list
'''
answers = []
one = [0] * n
def next_c(li=0, ni=0):
if ni == n:
answers.append(copy.copy(one))
return
for lj in range(li, len(l)):
one[ni] = l[lj]
next_c(lj + 1, ni + 1)
next_c()
return answers
def rate_vars(data_i, var_list):
new_var_name = '_'.join(var_list + ['rate'])
data_i[new_var_name] = data_i.apply(lambda x: x[var_list[0]] / x[var_list[1]] if x[var_list[1]] != 0 else np.nan,
axis=1)
return data_i
def minus_vars(data_i, var_list):
new_var_name = '_'.join(var_list + ['minus'])
data_i[new_var_name] = data_i[var_list[0]] - data_i[var_list[1]]
return data_i
def vals_format(val_list, agg):
if agg in ['rate', 'minus']:
if any(pd.isnull(val_list)):
return np.nan
elif agg == 'rate' and len(val_list) == 2:
if float(val_list[0]) == 0.0 and float(val_list[1]) == 0.0:
return 0
elif float(val_list[1]) == 0.0:
return np.inf
else:
return val_list[0] / val_list[1]
elif agg == 'minus' and len(val_list) == 2:
return val_list[0] - val_list[1]
else:
print('Error derivated')
non_null_val = list(filter(lambda x: not pd.isnull(x), val_list))
if len(non_null_val) == 0:
return np.nan
if agg == 'std':
return np.std(non_null_val, ddof=1)
elif agg == 'mean':
return np.mean(non_null_val)
elif agg in ['sum', 'min', 'max']:
return eval(agg)(non_null_val)
elif agg == 'same':
cou = Counter(val_list)
first = cou.most_common(1)
return first[0][1]
else:
print('error agg')
def normal_vars(data_i, agg=[], var_list=[]):
if len(agg) == 0 or len(var_list) <= 1:
return data_i
for agg_ii in agg:
new_var_name = '_'.join(var_list + [agg_ii])
print(new_var_name)
data_i[new_var_name] = data_i.apply(
lambda x: vals_format([x[var_list[ii]] for ii in range(len(var_list))], agg_ii), axis=1)
# data_i[new_var_name] = data_i.apply(
# lambda x: np.nan if all(pd.isnull([x[var_list[ii]] for ii in range(len(var_list))])) else eval(agg_ii)(
# [x[var_list[ii]] for ii in range(len(var_list))]), axis=1)
return data_i
def create_new_chn_name(new_var_info, var_info_dict, var_list, agg=[], cut_bin_num=5):
for agg_ii in agg:
new_dict = dict()
new_dict['var_name'] = '_'.join(var_list + [agg_ii])
new_dict['chn_name'] = '_'.join([var_info_dict[ii][1] for ii in var_list] + [agg_key_dict[agg_ii]])
new_dict['var_type'] = 'number'
new_dict['is_derivated'] = 1
new_dict['cut_bin_way'] = 'best_ks'
new_dict['cut_bin_num'] = cut_bin_num
new_var_info.append(new_dict)
return new_var_info
def derivate_vars(data_n, new_data_var_type, agg_list=[], col_list=[], cut_bin_num=5):
'''
:param data: 输入数据集
:param agg_list: 衍生统计方法,如'sum','min','max','mean','std'等
:param col_list:
:return:
'''
# data = pd.DataFrame({'col1': [1, 2, 5, np.nan], 'col2': [21, 2, 5, np.nan], 'col3': [0, 2, 5, np.nan],
# 'col4': ['a', 'b', 'c', 'd']})
# col_list=['col1', 'col2', 'col3']
# agg_list=['sum', 'mean']
result = data_n.copy()
result = normal_vars(result, agg=agg_list, var_list=col_list)
new_data_var_type = create_new_chn_name(new_data_var_type, chn_dict, col_list, agg=agg_list,
cut_bin_num=cut_bin_num)
# new_data = new_data[col_list].T
# agg_list_spec = [ii for ii in agg_list if ii in ['minus', 'rate']]
# 正常指标计算
# agg_list_normal = [ii for ii in agg_list if ii not in ['minus', 'rate']]
# if len(agg_list_normal)>0:
# new_col_names = ['_'.join(col_list + [ii]) for ii in agg_list_normal]
# new_result = new_data.agg(agg_list_normal).T
# new_result.columns = new_col_names
# new_data_var_type = create_new_chn_name(new_data_var_type, chn_dict, col_list, agg=agg_list_normal)
# if 'sum' in agg_list_normal:
# sum_var_name = '_'.join(col_list + ['sum'])
# is_null = [all(ii) for ii in np.array(new_data.isna().T)]
# new_result['col_isnull'] = is_null
# new_result[sum_var_name] = new_result.apply(lambda x: x[sum_var_name] if not x['col_isnull'] else np.nan,
# axis=1)
# new_result.drop(columns=['col_isnull'], inplace=True)
# result = pd.concat([data_n, new_result], axis=1)
# 特殊指标计算
# if 'rate' in agg_list_spec:
# if len(col_list) == 2:
# result = rate_vars(result, col_list)
# new_data_var_type = create_new_chn_name(new_data_var_type, chn_dict, col_list, agg=['rate'])
# else:
# print('ERROR:', col_list, 'rate')
# if 'minus' in agg_list_spec:
# if len(col_list) == 2:
# result = minus_vars(result, col_list)
# new_data_var_type = create_new_chn_name(new_data_var_type, chn_dict, col_list, agg=['minus'])
# else:
# print('ERROR:', col_list, 'minus')
return result, new_data_var_type
if __name__ == "__main__":
start_time = time.time()
agg_key_dict = {'sum': u'求和',
'rate': u'相除',
'minus': u'相减',
'max': u'最大值',
'min': u'最小值',
'std': u'标准差',
'mean': u'平均值'
}
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
tag = param_dic['tag']
key = param_dic['key']
cut_bin_num = param_dic['auto_bin_num']
datafile_input = param_dic['file_input']
derivate_var_list = param_dic['derivate_var_list']
derivate_agg_list = param_dic['derivate_agg_list']
derivate_var_n = param_dic['derivate_var_n']
output_data_file = param_dic['output_data_file']
output_datasource_file = param_dic['output_datasource_file']
data_var_type = pd.read_excel('./data/data_source.xlsx')
# 输入数据集
data = tool.read_file('./data/' + datafile_input)
chn_dict = data_var_type.set_index('var_name').T.to_dict('list')
# 输入衍生特征list及需衍生计算指标
# derivate_var_list = ['age',
# 'usermobileonlinedd',
# 'certi_city_level',
# 'phone_city_level', ]
# derivate_agg_list = ['sum', 'min', 'max', 'mean', 'minus', 'rate', 'std']
# # 举例两两组合衍生即n=2
# derivate_var_n = 2
# # 输出衍生变量数据集路径
# output_data_file = './data/data_derivated.csv'
# # 输出衍生变量中文名路径
# output_datasource_file = './data/data_source_derivated.csv'
all_list = combine(derivate_var_list, derivate_var_n)
new_data_var_type = []
fin_data = data.copy()
for var_l_i in all_list:
fin_data, new_data_var_type = derivate_vars(fin_data, new_data_var_type, agg_list=derivate_agg_list,
col_list=var_l_i,
cut_bin_num=cut_bin_num)
new_data_chn = pd.DataFrame(new_data_var_type)
new_data_chn = new_data_chn[['var_name', 'var_type', 'chn_name', 'is_derivated', 'cut_bin_way', 'cut_bin_num']]
new_data = fin_data[[key, tag] + list(new_data_chn['var_name'])]
print(10 * '*' + '输出衍生变量数据集' + output_data_file + 10 * '*')
new_data.to_csv(output_data_file, index=False, encoding='gbk')
print(10 * '*' + '输出衍生变量中文名' + output_datasource_file + 10 * '*')
new_data_chn.to_csv(output_datasource_file, index=False, encoding='gbk')
print(10 * '*' + 'finish d03 data derivated' + 10 * '*')
print('spend times:', time.time() - start_time)
<file_sep># -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
import d00_param
import imp
import tool
imp.reload(d00_param)
imp.reload(tool)
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
def data_split(df_, tag, test_size, oversample_num=1):
from sklearn import model_selection
if float(test_size) == 0.0:
df_train = df_
df_test = df_.drop(df_.index)
else:
df_y = df_[tag]
df_x = df_.drop(tag, axis=1)
x_train, x_test, y_train, y_test = model_selection.train_test_split(
df_x, df_y, test_size=test_size, random_state=128)
df_train = pd.concat([x_train, y_train], axis=1)
df_test = pd.concat([x_test, y_test], axis=1)
return df_train, df_test
def describle_quantile(data, ex_cols):
nd_var = list(set(data.columns.tolist()) - set(ex_cols))
describle = pd.DataFrame()
num_i = 0
for k in nd_var:
try:
percent = []
a = data[k]
# -2填充空值
a_1 = a.fillna(-2)
# print('has filled ', k)
list_a = np.sort(a_1.tolist())
for i in range(0, 100, 10):
percent.append(np.percentile(list_a, i))
describle[k] = percent
num_i += 1
except:
pass
print("已输入%d 列数据" % num_i)
describle['postition'] = [str(i * 10) + '%' for i in range(10)]
describle.set_index(["postition"], inplace=True)
return describle.T
def get_bin_image(fin_data, data, sheet1, sheet2):
import os
if os.path.exists('./image'):
pass
else:
os.makedirs('./image')
row = 0
var_list = data.columns
# var_list=['td_mobile_loan_all_orgcnt_30d']
var_name = list(fin_data.iloc[:, 0])
data_source = pd.read_excel('./data/data_source.xlsx', sheet_name='all')
string_var = data_source[data_source['var_type'] == 'str']['var_name'].tolist()
for num_ii in var_list:
if num_ii not in string_var:
plt.figure()
# plt.rcParams['font.sans-serif'] = ['SimHei']
# plt.rcParams['font.family'] = 'serif'
# plt.rcParams['axes.unicode_minus'] = False
image_file = './image/' + num_ii + '.png'
bp = data.boxplot(column=num_ii, sym='r*', meanline=False, showmeans=True, return_type='dict')
for box in bp['boxes']:
# change outline color
box.set(color='#7570b3', linewidth=2)
## change color and linewidth of the whiskers
for whisker in bp['whiskers']:
whisker.set(color='y', linewidth=2)
## change color and linewidth of the caps
for cap in bp['caps']: # 上下的帽子
cap.set(color='#7570b3', linewidth=2)
## change color and linewidth of the medians
for median in bp['medians']: # 中值
median.set(color='r', linewidth=2)
## change the style of fliers and their fill
for flier in bp['fliers']: # 异常值
flier.set(marker='o', color='k', alpha=0.5)
plt.savefig(image_file)
startrow = 3 + 25 * row
sheet2.write_string(startrow - 1, 0, num_ii)
sheet2.insert_image(startrow, 0, image_file) # 插入图片
start_num = var_name.index(num_ii) + 1
link = "internal:'箱线图'!A%s" % (str(startrow)) # 写超链接
sheet1.write_url(start_num, 0, link, string=num_ii)
row += 1
plt.close()
def rank(data_i, var_name):
data_col = data_i[var_name].value_counts()
data_col = data_col.reset_index()
data_col['rnk'] = data_col[var_name].rank(ascending=0, method='dense')
mode1 = ','.join([str(ii) for ii in data_col[data_col['rnk'] == 1]['index'].tolist()])
mode2 = ','.join([str(ii) for ii in data_col[data_col['rnk'] == 2]['index'].tolist()])
mode3 = ','.join([str(ii) for ii in data_col[data_col['rnk'] == 3]['index'].tolist()])
mode4 = ','.join([str(ii) for ii in data_col[data_col['rnk'] == 4]['index'].tolist()])
mode5 = ','.join([str(ii) for ii in data_col[data_col['rnk'] == 5]['index'].tolist()])
return [mode1, mode2, mode3, mode4, mode5]
def get_summary_data(newdata):
all_df = newdata.count()
all_df = all_df.reset_index()
all_df.columns = ['var_name', 'count']
all_df['rate'] = all_df['count'] / key_num
desc_df = newdata.describe(percentiles=percent_list).T
desc_df = desc_df.reset_index()
new_col = desc_df.columns
new_col = ['var_name' if i == 'index' else i for i in new_col]
desc_df.columns = new_col
fin_data = desc_df.copy()
skew = newdata.skew().reset_index()
skew.columns = ['var_name', 'skew']
kurt = newdata.kurt().reset_index()
kurt.columns = ['var_name', 'kurt']
fin_data = pd.merge(fin_data, skew, on='var_name', how='left')
fin_data = pd.merge(fin_data, kurt, on='var_name', how='left')
# fin_data['skew'] = list()
# fin_data['kurt'] = list()
fin_data['mode1'] = fin_data['var_name'].apply(lambda x: rank(newdata, x)[0])
fin_data['mode2'] = fin_data['var_name'].apply(lambda x: rank(newdata, x)[1])
fin_data['mode3'] = fin_data['var_name'].apply(lambda x: rank(newdata, x)[2])
fin_data['mode4'] = fin_data['var_name'].apply(lambda x: rank(newdata, x)[3])
fin_data['mode5'] = fin_data['var_name'].apply(lambda x: rank(newdata, x)[4])
new_col = fin_data.columns
col1 = [i for i in new_col if i.find('%') < 0]
col2 = [i for i in new_col if i.find('%') >= 0]
fin_p1 = fin_data[col1].copy()
# fin_p1['rate'] = fin_p1['count'] / key_num
fin_p2 = fin_data[col2].copy()
fin_data = pd.concat([fin_p1, fin_p2], axis=1)
fin_data = fin_data.drop(['count'], axis=1)
fin_data = pd.merge(all_df, fin_data, how='left', on='var_name')
fin_data.sort_values(by='rate', ascending=False, inplace=True)
fin_data.columns = ['特征中文名', '非空值计数', '覆盖率', '均值', '方差', '最小值', '最大值', '偏度', '峰度', '第1众数', '第2众数', '第3众数', '第4众数',
'第5众数'] + col2
return fin_data
def write_xlsx():
writer = pd.ExcelWriter(path_ + '_x_describe_info.xlsx')
# 特征分布情况
sheet1 = writer.book.add_worksheet('特征探查分布情况')
sheet1.freeze_panes(1, 1)
row_num, col_num = fin_data.shape
title_Style = writer.book.add_format(tool.title_Style)
cell_Style = writer.book.add_format(tool.cell_Style)
for jj in range(col_num):
val = fin_data.columns[jj]
sheet1.write(0, jj, val, title_Style)
for ii in range(row_num):
for jj in range(col_num):
val = fin_data.iloc[ii, jj]
if pd.isnull(val):
val = ''
if jj == 0:
new_dict = tool.cell_Style
new_dict['align'] = 'left'
fin_cell_Style = writer.book.add_format(new_dict)
elif jj == 1:
new_dict = tool.cell_Style
new_dict['num_format'] = '_ * #,##0_ ;_ * -#,##0_ ;_ * "-"??_ ;_ @_ '
fin_cell_Style = writer.book.add_format(new_dict)
elif jj == 2:
new_dict = tool.cell_Style
new_dict['num_format'] = '0.0%'
new_dict['align'] = 'center'
fin_cell_Style = writer.book.add_format(new_dict)
else:
fin_cell_Style = cell_Style
try:
sheet1.write(ii + 1, jj, val, fin_cell_Style)
except:
sheet1.write(ii + 1, jj, str(val), fin_cell_Style)
sheet1.set_column(0, 0, 20)
sheet1.set_column(1, fin_data.shape[1], 15)
# fin_data.to_excel(writer, 'summary',index=False)
# 箱线图
if bin_image:
sheet2 = writer.book.add_worksheet('箱线图')
get_bin_image(fin_data, newdata, sheet1, sheet2)
writer.save()
writer.close()
def var_type_format(x):
if (str(x).find('int') >= 0 or str(x).find('float') >= 0):
return 'number'
elif str(x) == 'object':
return 'str'
else:
return str(x)
def write_data_resource(df_i, auto_bin_num):
df_i_old = pd.DataFrame(
columns=['var_name', 'var_type', 'chn_meaning', 'is_derivated', 'cut_bin_way', 'cut_bin_num'])
if os.path.exists('./data/data_source.xlsx'):
df_i_old = pd.read_excel('./data/data_source.xlsx', sheet_name='all')
df_i_new = df_i.dtypes
df_i_new = df_i_new.reset_index()
df_i_new.columns = ['var_name', 'var_type']
df_i_new = df_i_new.copy()
df_i_new['var_type'] = df_i_new['var_type'].apply(var_type_format)
df_i_new.sort_values(by='var_type', ascending=False, inplace=True)
df_i_new['chn_meaning'] = np.nan
df_i_new['is_derivated'] = 0
df_i_new['cut_bin_way'] = 'best_ks'
df_i_new['cut_bin_num'] = auto_bin_num
df_i_new = df_i_new[-df_i_new['var_name'].isin(df_i_old['var_name'])]
df_i_new = pd.concat([df_i_old, df_i_new], axis=0)
df_i_new.to_excel('./data/data_source.xlsx', sheet_name='all', index=False)
print(10 * '*' + '请完善字段中文名、数据类型文件(路径为./data/data_source.xlsx)如已完成请忽略' + 10 * '*')
def d01_main(save_path, data, tag, test_size):
print(10 * '*' + 'start to split data ...' + 10 * '*')
df_train, df_test = data_split(data, tag, test_size)
print(10 * '*' + 'finish split data ...' + 10 * '*')
print(10 * '*' + 'start to describle quantile' + 10 * '*')
write_xlsx()
df_train.to_pickle('./data/' + save_path + '_df_train.pkl')
df_test.to_pickle('./data/' + save_path + '_df_test.pkl')
print(10 * '*' + 'finish describle quantile' + 10 * '*')
if __name__ == "__main__":
with tool.Timer() as t:
param_dic = d00_param.param_dic
import os
if os.path.exists('./data'):
pass
else:
os.makedirs('./data')
# 将数据存放在创建的运行目录下的data文件夹内
file_in = './data/' + param_dic['data_file']
percent_list = param_dic['percentiles']
project_name = param_dic['project_name']
tag = param_dic['tag']
key = param_dic['key']
bin_image = param_dic['bin_image']
test_size = param_dic['test_size']
ex_cols = param_dic['ex_cols']
auto_bin_num = param_dic['auto_bin_num']
data = tool.read_file(file_in)
path_ = tool.prepare_path(project_name, 'd01_')
data = data[data[tag] != 2]
write_data_resource(data, auto_bin_num)
key_num = data[key].count() # 总样本数
data_col = list(set(data.columns.tolist()) - set([key]))
newdata = data[data_col]
fin_data = get_summary_data(newdata)
d01_main(project_name, data, tag, test_size)
print(t.secs)
<file_sep># -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
def catch_score(x, group):
for i in group:
if x > float(eval(i)[0]) and x <= float(eval(i)[1]):
bin = i
try:
return bin
except:
print(x, eval(i)[0])
bin = 0
return bin
def func_good(x):
if x == 1:
y = 0
else:
y = 1
return y
def func_bad(x):
if x == 0:
y = 0
else:
y = 1
return y
def group_score(data, code, cut, score_name=None):
'''
:param data:
:param code:
:param cut: qcut/cut/10score_cut/uncut
:param score_name: 可选填,当score的名字自定义非'score'时
:return:
'''
df_rs = data.copy()
list = df_rs.index.tolist()
df_rs.ix[:, 'no'] = [ii for ii in range(len(list))]
if score_name:
df_rs['score'] = df_rs[score_name]
try:
if cut == 'qcut':
a = pd.qcut(df_rs['score'], 10)
df_rs['score_group'] = a
elif cut == 'cut':
a = pd.cut(df_rs['score'], 10)
df_rs['score_group'] = a
elif cut == 'uncut':
df_rs['score_group'] = df_rs['score'][:]
elif cut == '10score_cut':
group = ['[' + str(i) + ',' + str(i + 10) + ']' for i in range(100, 1300, 10)]
df_rs['score_group'] = df_rs['score'].map(lambda x: catch_score(x, group))
elif cut == '2score_cut':
group = ['[' + str(i) + ',' + str(i + 10) + ']' for i in range(100, 1300, 2)]
df_rs['score_group'] = df_rs['score'].map(lambda x: catch_score(x, group))
elif cut == 'artificial':
df_rs['score_group'] = df_rs['score_bin']
else:
print('error! check cut_value,cut_method changed to uncut ')
df_rs['score_group'] = df_rs['score'][:]
except:
print('error! check cut_value,cut_method changed to uncut ')
df_rs['score_group'] = df_rs['score'][:]
df_rs['good'] = df_rs[code].map(lambda x: func_good(x))
df_rs['bad'] = df_rs[code].map(lambda x: func_bad(x))
b = df_rs.groupby(['score_group', ])['no', 'good', 'bad'].sum()
df_gp = pd.DataFrame(b)
# print df_gp
return df_gp
def gb_add_woe(data, code, cut, score_name=None):
if score_name:
df_gp = group_score(data, code, cut, score_name)
else:
df_gp = group_score(data, code, cut)
df_gp.ix[:, 'bad_rate'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp['total_cnt'] = df_gp['bad'] + df_gp['good']
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
# df_gp['bad_pct_alone']=df_gp['bad']/(df_gp['bad']+df_gp['good'])
df_gp['bad_pct'] = df_gp['bad'].apply(lambda x: x / float(bad_sum))
df_gp['good_pct'] = df_gp['good'].apply(lambda x: x / float(good_sum))
# df_gp['odds'] = df_gp.apply(lambda x: x['good_pct'] - x['bad_pct'])
df_gp['odds'] = df_gp['good_pct'] / df_gp['bad_pct']
df_gp.ix[:, 'Woe'] = np.log(df_gp['good_pct'] / df_gp['bad_pct'])
df_gp.ix[:, 'IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp.ix[:, 'bad_cnt'] = bad_cnt
df_gp.ix[:, 'good_cnt'] = good_cnt
df_gp.ix[:, 'b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'KS'] = df_gp['b_c_p'] - df_gp['g_c_p']
df_gp['bin'] = df_gp.index.map(lambda x: str(x)).tolist()[:]
# df_gp['bin'] = df_gp.index.map(lambda x: str(x) + ')').tolist()[:]
df_gp['bin_pct'] = (df_gp['good'] + df_gp['bad']) / (bad_sum + good_sum)
df_gp = df_gp.reset_index(drop=True)
ks_max = df_gp['KS'].max()
df_gp = df_gp[['bin', 'total_cnt', 'good', 'bad', 'bin_pct', 'bad_rate', 'Woe', 'KS', 'IV']]
# print df_gp
return ks_max, df_gp
def auc(df, label='label', predict='predict', prob=False):
"""
功能:根据样本实际标签和预测概率(分数)快速计算auc值。
参数:
df: pd.DataFrame,至少包含标签号预测结果列;
label: 样本实际标签(0, 1);
predict: 预测结果(分数或概率均可);
prob: predict是否为概率,根据实际情况设置,默认False;
输出:auc值。
"""
if prob:
df.sort_values(by=predict, ascending=False, inplace=True)
else:
df.sort_values(by=predict, ascending=True, inplace=True)
rank = list(reversed(range(1, df.shape[0] + 1)))
df['rank'] = rank
mean = df.groupby([predict])['rank'].mean().reset_index()
mean.columns = [predict, 'rank_mean']
df = pd.merge(df, mean, on=predict)
print(df)
df[label].value_counts()
N, M = df[label].value_counts().sort_index().values
print(df[label].value_counts().sort_index())
formula1 = df[df[label]==1]['rank'].sum()
formula2 = M * (M + 1) / 2
return np.round((formula1 - formula2) / (M * N), 4)
def ks_auc():
df_rs_score=pd.read_csv('./new_data.csv')
time_cut=[ 'd01:1-14','d02:15-30', 'd03:31-60']
time_name=['近14天','近30天','近60天']
ks_value=[]
AUC1=[]
AUC2=[]
from sklearn.metrics import roc_auc_score
for ii in range(3):
new_l=time_cut[:ii+1]
df_rs_score_ii=df_rs_score[df_rs_score['gap_days'].isin(new_l)]
print(df_rs_score_ii.shape)
ks_max_uncut, df_gp_uncut = gb_add_woe(df_rs_score_ii, 'credit_status', 'uncut',score_name='nydd_prea_score')
auc1=auc(df_rs_score_ii,label='credit_status', predict='nydd_prea_score')
Y=df_rs_score_ii['credit_status']
p=1-df_rs_score_ii['nydd_prea_p']
auc2 = roc_auc_score(Y, p)
print(ks_max_uncut)
ks_value.append(ks_max_uncut)
AUC1.append(auc1)
AUC2.append(auc2)
df=pd.DataFrame([time_name,ks_value,AUC1,AUC2])
print(df)
df.to_csv('result.csv',index=False)
ks_auc()
<file_sep># -*- coding:utf-8 -*-
import pandas as pd
import statsmodels.api as sm
# import pylab as pl
import numpy as np
import math
# import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score
from binning.drawwoe import draw_woe
from tool import corr_img
import tool
import imp
imp.reload(tool)
def func_good(x):
if x == 1:
y = 0
else:
y = 1
return y
def func_bad(x):
if x == 0:
y = 0
else:
y = 1
return y
# def group_score(data,code):
# df_rs=data.copy()
# list=df_rs.index.tolist()
# df_rs.ix[:,'no']=list
# a=pd.qcut(df_rs['p'],10)
# df_rs.ix[:,'p_group']=a
# df_rs['good']=df_rs[code].map(lambda x:func_good(x))
# df_rs['bad']=df_rs[code].map(lambda x:func_bad(x))
# b=df_rs.groupby(['p_group',])['no','good','bad'].sum()
# df_gp=pd.DataFrame(b)
# return df_gp
def group_score(data, code, cut, score_name=None):
'''
:param data:
:param code:
:param cut: qcut/cut/10score_cut/uncut
:param score_name: 可选填,当score的名字自定义非'score'时
:return:
'''
df_rs = data.copy()
list = df_rs.index.tolist()
df_rs.ix[:, 'no'] = [ii for ii in range(len(list))]
if score_name:
df_rs['score'] = df_rs[score_name]
try:
if cut == 'qcut':
a = pd.qcut(df_rs['score'], 10)
df_rs['score_group'] = a
elif cut == 'cut':
a = pd.cut(df_rs['score'], 10)
df_rs['score_group'] = a
elif cut == 'uncut':
df_rs['score_group'] = df_rs['score'][:]
elif cut == '10score_cut':
group = ['[' + str(i) + ',' + str(i + 10) + ']' for i in range(100, 1300, 10)]
df_rs['score_group'] = df_rs['score'].map(lambda x: catch_score(x, group))
elif cut == '2score_cut':
group = ['[' + str(i) + ',' + str(i + 10) + ']' for i in range(100, 1300, 2)]
df_rs['score_group'] = df_rs['score'].map(lambda x: catch_score(x, group))
elif cut == 'artificial':
df_rs['score_group'] = df_rs['score_bin']
else:
print('error! check cut_value,cut_method changed to uncut ')
df_rs['score_group'] = df_rs['score'][:]
except:
print('error! check cut_value,cut_method changed to uncut ')
df_rs['score_group'] = df_rs['score'][:]
df_rs['good'] = df_rs[code].map(lambda x: func_good(x))
df_rs['bad'] = df_rs[code].map(lambda x: func_bad(x))
b = df_rs.groupby(['score_group', ])['no', 'good', 'bad'].sum()
df_gp = pd.DataFrame(b)
# print df_gp
return df_gp
# df_score_gp=group_score(final_score,'tag','reborrow_score')
def catch_score(x, group):
for i in group:
if x > float(eval(i)[0]) and x <= float(eval(i)[1]):
bin = i
try:
return bin
except:
print(x, eval(i)[0])
bin = 0
return bin
# df_score['score_group']=df_score['score'].map(lambda x : catch_score(x,group))
def gb_add_woe(data, code, cut, score_name=None):
if score_name:
df_gp = group_score(data, code, cut, score_name)
else:
df_gp = group_score(data, code, cut)
df_gp.ix[:, 'bad_rate'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp['total_cnt'] = df_gp['bad'] + df_gp['good']
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
# df_gp['bad_pct_alone']=df_gp['bad']/(df_gp['bad']+df_gp['good'])
df_gp['bad_pct'] = df_gp['bad'].apply(lambda x: x / float(bad_sum))
df_gp['good_pct'] = df_gp['good'].apply(lambda x: x / float(good_sum))
# df_gp['odds'] = df_gp.apply(lambda x: x['good_pct'] - x['bad_pct'])
df_gp['odds'] = df_gp['good_pct'] / df_gp['bad_pct']
df_gp.ix[:, 'Woe'] = np.log(df_gp['good_pct'] / df_gp['bad_pct'])
df_gp.ix[:, 'IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp.ix[:, 'bad_cnt'] = bad_cnt
df_gp.ix[:, 'good_cnt'] = good_cnt
df_gp.ix[:, 'b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'KS'] = df_gp['b_c_p'] - df_gp['g_c_p']
df_gp['bin'] = df_gp.index.map(lambda x: str(x)).tolist()[:]
# df_gp['bin'] = df_gp.index.map(lambda x: str(x) + ')').tolist()[:]
df_gp['bin_pct'] = (df_gp['good'] + df_gp['bad']) / (bad_sum + good_sum)
df_gp = df_gp.reset_index(drop=True)
ks_max = df_gp['KS'].max()
df_gp = df_gp[['bin', 'total_cnt', 'good', 'bad', 'bin_pct', 'bad_rate', 'Woe', 'KS', 'IV']]
# print df_gp
return ks_max, df_gp
# df_gp=gb_add_woe(data,code,'uncut',score_name=i)
def cal_score(data, base_score, double_score, odds):
'''
:param data: df_['id','tag'] 为了方便要统一一下字段名字_(:зゝ∠)_
:param odds: 全局bad/good
:param result:模型训练结果,以result格式
:return:每个客户的总分
'''
B = double_score / math.log(2)
A = base_score + B * math.log(odds)
df_rs = data.copy()
df_rs['p_'] = df_rs['p'].apply(lambda x: 1 - float(x))
df_rs['score'] = np.array([A for _ in range(len(df_rs))]) + \
np.array([B for _ in range(len(df_rs))]) * np.log(df_rs.ix[:, 'p'] / df_rs.ix[:, 'p_'])
# df_rs['score'].astype(int)
return df_rs, A, B
def cal_scorei(woe_dic, base_score, double_score, odds, result):
'''
:param woe_dic: 变量的woe字典,varname
:param base_score:
:param double_score:
:param odds: 全局good/bad
:param result:模型训练结果,以result格式,varname_woe
:return:返回每个入参变量的小分
'''
B = double_score / math.log(2)
A = base_score + B * math.log(odds)
Intercept = result.params['intercept']
N = len(result.params) - 1
summary = []
# print('prepared')
for i in result.params.index.tolist():
if i != 'intercept':
coef_i = result.params[i]
dic_i = woe_dic[i[:-4]]
for j in dic_i.keys():
woe_i = dic_i[j]
score_i = (woe_i * coef_i + Intercept / N) * B + A / N
summary.append([i, j, score_i])
summary.append(['', '', ''])
summary_df = pd.DataFrame(summary, columns=['var', 'bin', 'score'])
return summary_df
# cal_scorei(dic_all,550,40,30,result1)
#
#
# col_1,result,vars_dic=func_stepwise_1(var,mm,'tag')
#
# summary_df=cal_scorei(xhd_woe_dic,580,50,0.1,result)
def cal_bin_num(bin, ):
pass
def cal_PSI_var(train, test, train_vars, save_path):
'''
:param data1:使用训练集的df_gp['bin','amount']
:param data2:使用测试集的df_score(总分)
:return: 计算两个data的PSI,
:psi = sum((实际占比-预期占比)*ln(实际占比/预期占比))
'''
psi = {}
from pandas import ExcelWriter
writer = ExcelWriter(save_path + '_PSI_INFO.xlsx')
num = 0
for var_name in train_vars:
train_i = train[var_name].value_counts(True)
test_i = test[var_name].value_counts(True)
a = pd.DataFrame(train_i)
a['test_pct'] = test_i
a.columns = ['train_pct', 'test_pct']
a['var_name'] = var_name
a['psi'] = (a['train_pct'] - a['test_pct']) * np.log(a['train_pct'] / a['test_pct'])
a.to_excel(writer, 'detail', startrow=num)
num += len(a) + 3
psi[var_name] = sum(a['psi'])
PSI_DF = pd.DataFrame(psi, index=['PSI']).T
PSI_DF.to_excel(writer, 'psi_summary', startrow=0)
writer.save()
return PSI_DF
# def func_cal(data,key,tag,vars,base_score,double_score,woe_dic,save_path,method,enable_test=False):
# '''
# :param data: 客户数据['id','tag']
# :param X: data[train_cols]
# :param Y: data[tag]
# :param base_score:
# :param woe_dic:m_data所返回的变量woe字典
# :param v: odds
# :return: 根据已选出来的变量,生成模型结果报告
# '''
# from pandas import ExcelWriter
# writer=ExcelWriter(save_path)
# rs=data.copy()
# Y=data[tag]
# print 'stage1 : 逻辑回归结果:'
# if method=='REPORT':
# X=data[vars]
# logit = sm.Logit(Y,X)
# result1 = logit.fit()
# elif method=='STEPWISE':
# train_vars = data.columns.tolist()
# train_vars.remove(key)
# train_vars.remove(tag)
# if 'Unnamed: 0' in train_vars:
# train_vars.remove('Unnamed: 0')
# # X = data[train_vars]
# col_1, result1, vars_dic = func_stepwise_1(train_vars, data, tag)
# print result1.summary()
# p = result1.predict().tolist()
# auc = roc_auc_score(Y, p)
# rs['p']=p
# odds=float(len(Y[Y==0]))/float(len(Y[Y==1]))
# print 'stage2: 开始计算小分:'
# # score_i_df=cal_scorei(woe_dic, base_score, double_score, odds, result1)
# # score_i_df.to_excel(writer, 'score_i', startrow=0)
# print 'stage3: 开始计算单个客户得分:'
# df_rs_score = cal_score(rs, base_score, double_score, odds)
# df_rs_score.to_excel(writer,'cust_score',startrow=0)
# print df_rs_score[:3]
# print 'stage4: 开始计算KS:'
# ks_max_uncut, df_gp_uncut = gb_add_woe(df_rs_score,tag,'uncut')
# ks_max_cut, df_gp_cut = gb_add_woe(df_rs_score,tag,'cut')
# ks_max_qcut, df_gp_qcut = gb_add_woe(df_rs_score,tag,'qcut')
# ks=[auc,ks_max_uncut,ks_max_cut,ks_max_qcut]
# df_gp_cut.to_excel(writer,'df_gp_score',startrow=0)
# df_gp_qcut.to_excel(writer,'df_gp_score',startrow=len(df_gp_cut)+3)
# ks_df=pd.DataFrame(ks,columns=['describe'],index=['auc','ks_max_uncut','ks_max_cut','ks_max_qcut'])
# ks_df.to_excel(writer,'result_summary',startrow=0)
# writer.save()
# print '--------AUC: '+str(auc)+'---------'
# print '---------------KS: -----------------'
# print ks_df
# print '----------------------------------'
# print df_gp_cut
# return result1,rs,auc,df_gp_cut
def cal_ks(result1, data, tag, base_score, double_score):
'''
:param data: 客户数据['id','tag']
:param X: data[train_cols]
:param Y: data[tag]
:param base_score:
:param woe_dic:m_data所返回的变量woe字典
:param v: odds
:return: 根据已选出来的变量,生成模型结果报告
'''
rs = data.copy()
Y = data[tag]
print(result1.summary2())
p = result1.predict().tolist()
auc = roc_auc_score(Y, p)
rs['p'] = p
odds = float(len(Y[Y == 0])) / float(len(Y[Y == 1]))
# print 'stage3: 开始计算单个客户得分:'
df_rs_score, A, B = cal_score(rs, base_score, double_score, odds)
# print 'stage4: 开始计算KS:'
ks_max_uncut, df_gp_uncut = gb_add_woe(df_rs_score, tag, 'uncut')
ks_max_cut, df_gp_cut = gb_add_woe(df_rs_score, tag, 'cut')
ks_max_qcut, df_gp_qcut = gb_add_woe(df_rs_score, tag, 'qcut')
ks = [auc, ks_max_uncut, ks_max_cut, ks_max_qcut]
ks_df = pd.DataFrame(ks, columns=['describe'], index=['auc', 'ks_max_uncut', 'ks_max_cut', 'ks_max_qcut'])
print('--------AUC: ' + str(auc) + '---------')
print('---------------KS: -----------------')
print(ks_df)
return ks_df, odds, A, B
def cal_ks_test(result, test_data, tag, base_score=550, double_score=-40, odds=30):
'''
:param data: 客户数据['id','tag']
:param X: data[train_cols]
:param Y: data[tag]
:param base_score:
:param woe_dic:m_data所返回的变量woe字典
:param v: odds
:return: 根据已选出来的变量,生成模型结果报告
'''
rs = test_data.copy()
predict_cols = result.params.index.tolist()
rs['intercept'] = 1.0
p = result.predict(rs[predict_cols])
rs['p'] = p
Y = rs[tag]
auc = roc_auc_score(Y, p)
df_rs_score, A, B = cal_score(rs, base_score, double_score, odds)
ks_max_uncut, df_gp_uncut = gb_add_woe(df_rs_score, tag, 'uncut')
ks_max_cut, df_gp_cut = gb_add_woe(df_rs_score, tag, 'cut')
ks_max_qcut, df_gp_qcut = gb_add_woe(df_rs_score, tag, 'qcut')
ks = [auc, ks_max_uncut, ks_max_cut, ks_max_qcut]
ks_df = pd.DataFrame(ks, columns=['describe'], index=['AUC', 'KS_不切分', 'KS_等距切分', 'KS_等频切分'])
# print('--------AUC: ' + str(auc) + '---------')
# print('---------------KS: -----------------')
# print(ks_df)
# print('---------------cut:-----------------')
# print (df_gp_cut)
# return df_rs_score
return df_gp_uncut, df_gp_cut, df_gp_qcut, ks_df, p, df_rs_score
def func_report(data, result, tag, base_score, double_score, save_path, test, info=None, odds=30,
score_detail_btn=False, data_dic=dict()):
'''
:param data: 训练集
:param result: 模型训练结果
:param tag: Y标签
:param base_score: 基准分
:param double_score: 翻倍分数
:param save_path: 存储路径,默认当前目录下,不带.xlsx
:param test: 测试集
:param info: info表的detail页签
:param odds: 翻倍对应好坏比例,默认30:1
:param score_detail_btn: 是否输出模型分明细
:return:
'''
from pandas import ExcelWriter
writer = pd.ExcelWriter(save_path + '_result.xlsx')
title_Style = writer.book.add_format(tool.title_Style)
cell_Style = writer.book.add_format(tool.cell_Style)
# formats = '#,##0.00'
rs = data.copy()
ts_data=test.copy()
Y_train = data[tag]
Y_test= test[tag]
ts_data['intercept']=1.0
print('stage1 : LOGISTIC RESULT:')
print(result.summary2())
train_col = result.params.index.tolist()
p_train = result.predict(data[train_col]).tolist()
p_test = result.predict(ts_data[train_col]).tolist()
auc_train = roc_auc_score(Y_train, p_train)
# auc_test = roc_auc_score(Y_test, p_test)
# roc
from sklearn import metrics
from sklearn.metrics import roc_curve
from matplotlib import pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
lr_fpr_train, lr_tpr_train, lr_thresholds = roc_curve(Y_train, p_train)
lr_fpr_test, lr_tpr_test, lr_thresholds = roc_curve(Y_test, p_test)
# 分别计算这两个模型的auc的值, auc值就是roc曲线下的面积
lr_roc_auc_train = metrics.auc(lr_fpr_train, lr_tpr_train)
lr_roc_auc_test = metrics.auc(lr_fpr_test, lr_tpr_test)
plt.figure(figsize=(8, 8))
plt.plot([0, 1], [0, 1], '--', color='r')
plt.plot(lr_fpr_train, lr_tpr_train, label='训练集(AUC = %0.2f)' % lr_roc_auc_train)
plt.plot(lr_fpr_test, lr_tpr_test, label='测试集(AUC = %0.2f)' % lr_roc_auc_test)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.title('ROC')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.legend()
ROC_IMG=save_path + "_ROC.png"
plt.savefig(ROC_IMG)
#
rs['p'] = p_train
# odds=float(len(Y[Y==0]))/float(len(Y[Y==1]))
# odds=30
print('stage1.5:PREPARE VAR RESULT:')
num = 0
# tt = func_tt_vardescrible(data, test, [i[:-4] + '_bin' for i in train_col if '_woe' in i], save_path[:-5], tag)
print('stage3: BEGIN TO CAL SCORE_I:()')
df_rs_score1, A, B = cal_score(rs, base_score, double_score, odds)
# df_rs_score1.to_excel(writer,sheetname='score_detail')
print('stage4: BEGIN TO CAL KS :')
ks_max_uncut, df_gp_uncut = gb_add_woe(df_rs_score1, tag, 'uncut')
ks_max_cut, df_gp_cut = gb_add_woe(df_rs_score1, tag, 'cut')
ks_max_qcut, df_gp_qcut = gb_add_woe(df_rs_score1, tag, 'qcut')
ks = [auc_train, ks_max_uncut, ks_max_cut, ks_max_qcut]
ks_df = pd.DataFrame(ks, columns=['describe'], index=['AUC', 'KS_不切分', 'KS_等距切分', 'KS_等频切分'])
df_gp_uncut2, df_gp_cut2, df_gp_qcut2, ks_df2, p2, df_rs_score2 = cal_ks_test(result, test, tag, base_score,
double_score, odds)
ks_df=ks_df.reset_index()
ks_df.columns=['训练集','describe']
ks_df2 = ks_df2.reset_index()
ks_df2.columns = ['测试集', 'describe']
# --------------------------------
df_score = df_rs_score1.append(df_rs_score2)
# 模型AUC/KS结果
# ks_df.to_excel(writer, '模型AUC_KS结果', startrow=0, index=False)
ws_ks_df = writer.book.add_worksheet('模型AUC_KS结果')
ws1 = writer.book.add_worksheet('最终入模特征')
ws2 = writer.book.add_worksheet('评分卡刻度及公式')
ws3 = writer.book.add_worksheet('模型各特征分箱明细(自动分箱)')
row_num = ks_df.shape[0]
summary_df = ks_df.fillna('')
ws_ks_df.write_row(0, 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws_ks_df.write_row(1 + ii, 0, summary_df.loc[ii,], cell_Style)
row_num = ks_df2.shape[0]
summary_df = ks_df2.fillna('')
ws_ks_df.write_row(3+ks_df.shape[0], 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws_ks_df.write_row(4+ks_df.shape[0] + ii, 0, summary_df.loc[ii,], cell_Style)
ws_ks_df.set_column(0, summary_df.shape[1], 20)
ws_ks_df.insert_image(6+ks_df.shape[0] + row_num, 0, ROC_IMG)
# ks_df2.to_excel(writer, '模型AUC_KS结果', startrow=ks_df.shape[0] + 3, index=False)
ks, gp = gb_add_woe(df_score, tag, '10score_cut')
df_title = pd.DataFrame(columns=[u'模型分等距分箱'])
df_title.to_excel(writer, '训练集各分数段分布情况', startrow=0)
df_gp_cut.to_excel(writer, '训练集各分数段分布情况', startrow=1)
df_title = pd.DataFrame(columns=[u'模型分等频分箱'])
df_title.to_excel(writer, '训练集各分数段分布情况', startrow=df_gp_cut.shape[0] + 3)
df_gp_qcut.to_excel(writer, '训练集各分数段分布情况', startrow=df_gp_cut.shape[0] + 4)
df_title = pd.DataFrame(columns=[u'模型分等距分箱'])
df_title.to_excel(writer, '测试集各分数段分布情况', startrow=0)
df_gp_cut2.to_excel(writer, '测试集各分数段分布情况', startrow=1)
df_title = pd.DataFrame(columns=[u'模型分等频分箱'])
df_title.to_excel(writer, '测试集各分数段分布情况', startrow=df_gp_cut.shape[0] + 3)
df_gp_qcut2.to_excel(writer, '测试集各分数段分布情况', startrow=df_gp_cut.shape[0] + 4)
gp.to_excel(writer, '训练&测试集汇总10分档分布情况', startrow=0)
result_df = pd.DataFrame({'params': list(result.params.index),
'coef': list(result.params),
'p_value': list(result.pvalues)})
result_df['特征简称'] = result_df['params'].apply(lambda x: x[:-4] if x != 'intercept' else x)
result_df['特征中文名'] = result_df['特征简称'].apply(
lambda x: data_dic[x][u'特征中文名'] if x != 'intercept' else np.nan)
result_df['IV'] = result_df['特征简称'].apply(
lambda x: data_dic[x]['IV'] if x != 'intercept' else np.nan)
result_df[u'覆盖率'] = result_df['特征简称'].apply(
lambda x: data_dic[x][u'覆盖率'] if x != 'intercept' else np.nan)
result_df.sort_values('IV', ascending=False, inplace=True)
# result_df.to_excel(writer, 'Final Model Vars')
# 输出评分明细
if score_detail_btn:
df_score.to_excel(writer, 'modeling_score_details')
xpath_ = save_path.replace( 'd04_','d02_')
info_dt = pd.read_excel(xpath_ + '_info.xlsx', sheet_name='特征分箱明细')
if info:
var_list = [i[:-4] for i in result.params.index if '_woe' in i]
draw_woe(info, var_list, save_path)
# 评分卡公式参数
df_param = pd.DataFrame([{'odds': odds, 'A': A, 'B': B}])
row_num = df_param.shape[0]
summary_df = df_param.fillna('')
ws2.write_row(0, 0, summary_df.columns,title_Style)
for ii in range(row_num):
ws2.write_row(1 + ii, 0, summary_df.loc[ii,],cell_Style)
ws2.set_column(0, df_param.shape[1], 20)
base_str1=''
for ii in result_df['特征简称']:
if ii != 'intercept':
base_str1=base_str1+"+ %s * %s "%(ii+'_coef',ii+'_woe')+'\n'
else:
base_str1=base_str1+"+ intercept "+'\n'
fin_str1="Score = A + B * [ %s ]"%(base_str1)
ws2.write(row_num + 2, 0, '评分卡公式')
ws2.write(row_num + 3, 0, fin_str1)
# f = open(save_path + '_fin_model_parms.txt', 'w')
# f.write(','.join(['odds', 'A', 'B']) + '\n')
# f.write(','.join([str(odds), str(A), str(B)]))
# f.close()
# out_vars = [u'm12验证码通知平台']
var_dict=dict()
# 最终入模特征相关性热力图
out_vars = [ii for ii in result_df[u'特征简称'] if ii != 'intercept']
out_img = []
if len(out_vars) >= 1:
df_corr = data[[ii + '_woe' for ii in out_vars]]
df_corr.columns=out_vars
dfData = df_corr.corr()
dfData = dfData.reset_index()
out_img = corr_img(df_corr, save_path)
# 最终入模特征分箱明细
coef_dic = result_df[[u'特征简称','coef']].set_index(u'特征简称').to_dict('index')
startrow=0
for var_i in out_vars:
info_dt_i = info_dt[info_dt[u'var_name'] == var_i]
info_dt_i.columns = [var_i] + list(info_dt_i.columns[1:])
coef=coef_dic[var_i]['coef']
info_dt_i=info_dt_i.copy()
info_dt_i=info_dt_i.reset_index(drop=True)
info_dt_i[u'分箱对应打分']=coef*info_dt_i['Woe']*B
var_dict[var_i] = startrow
row_num = info_dt_i.shape[0]
summary_df = info_dt_i.fillna('')
ws3.write_row(startrow, 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws3.write_row(1 + ii+startrow, 0, summary_df.loc[ii,], cell_Style)
# info_dt_i.to_excel(writer, 'Final Model Vars Details(auto)', startrow=startrow,index=False)
startrow=startrow+info_dt_i.shape[0]+3
ws3.set_column(0, 0, 25)
ws3.set_column(1, info_dt_i.shape[1], 15)
row_num = result_df.shape[0]
summary_df = result_df.fillna('')
ws1.write(0, 0, '1.最终入模特征', title_Style)
ws1.write_row(1, 0, summary_df.columns,title_Style)
fin_vars = summary_df[u'特征简称']
for ii in range(row_num):
ws1.write_row(2 + ii, 0, summary_df.loc[ii,],cell_Style)
var_name = fin_vars[ii]
if var_name!='intercept':
start_num = var_dict[var_name] + 1
link = "internal:'模型各特征分箱明细(自动分箱)'!A%s" % (str(start_num)) # 写超链接
ws1.write_url(ii + 2, 3, link, string=var_name)
ws1.set_column(0,0, 30)
ws1.set_column(1, result_df.shape[1], 15)
if out_img:
ws1.write(row_num + 4, 0, '2.入模特征相关性系数矩阵及热力图',title_Style)
row_num_df = dfData.shape[0]
summary_df = dfData.fillna('')
ws1.write_row(row_num + 5, 0, summary_df.columns,title_Style)
for ii in range(row_num_df):
ws1.write_row(row_num + 6 + ii, 0, summary_df.loc[ii,],cell_Style)
ws1.insert_image(row_num + 8+row_num_df, 0, out_img)
ws1.set_column(1, dfData.shape[1], 15)
writer.save()
# print('--------AUC: ' + str(auc) + '---------')
# print('---------------KS: -----------------')
# print(ks_df)
# print('----------------------------------')
# print(df_gp_cut)
# draw_roc([[Y, p], [test[tag], p2]],['train','test'])
return df_score
def cal_woedf_i(df_rs, bin, tag):
df_rs['good'] = df_rs[tag].map(lambda x: func_good(x))
df_rs['bad'] = df_rs[tag].map(lambda x: func_bad(x))
df_gp = df_rs.groupby([bin])['good', 'bad'].sum()
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
df_gp['pct_default'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp = df_gp.sort_values('pct_default')
df_gp['bad_pct'] = df_gp['bad'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp['good_pct'] = df_gp['good'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp['Woe'] = np.log(df_gp['good_pct'] / df_gp['bad_pct'])
df_gp['IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp['bad_cnt'] = bad_cnt
df_gp['good_cnt'] = good_cnt
df_gp['b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp['g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp['KS'] = df_gp['g_c_p'] - df_gp['b_c_p']
df_gp['KS'] = df_gp['KS'].map(lambda x: abs(x))
return df_gp
def prepare_report_vardetail_cal(i, train, dic_all):
df_i = pd.DataFrame(dic_all[i[:-4]], index=[i[:-4]]).T
# df_i=pd.DataFrame(dic_woe_all[i[:-4]],index=[i[:-4]]).T
df_ii = cal_woedf_i(train, i, 'tag')
df_ii['woe'] = df_ii['Woe'].map(lambda x: str(x)[:10]).astype(float)
df_ii = df_ii.reset_index(drop=True)
df_i['bin'] = df_i.index[:]
df_i = df_i.reset_index(drop=True)
df_i[i[:-4]] = df_i[i[:-4]].map(lambda x: str(x)[:10]).astype(float)
df = pd.merge(df_ii, df_i, how='left', left_on='woe', right_on=i[:-4])
return df
def cal_ks_tt(df_rs, bin, tag):
df_rs.ix[:, 'good'] = df_rs[tag].map(lambda x: func_good(x))
df_rs.ix[:, 'bad'] = df_rs[tag].map(lambda x: func_bad(x))
df_gp = df_rs.groupby([bin])['good', 'bad'].sum()
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp.ix[:, 'bad_cnt'] = bad_cnt
df_gp.ix[:, 'good_cnt'] = good_cnt
df_gp['pct_bin'] = (df_gp['good'] + df_gp['bad']) / (bad_sum + good_sum)
df_gp['pct_default'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp['bad_pct'] = df_gp['bad'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp['good_pct'] = df_gp['good'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp['Woe'] = [0 if 'inf' in str(ii) else ii for ii in np.log(df_gp['good_pct'] / df_gp['bad_pct'])]
df_gp['IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
df_gp.ix[:, 'b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'ks'] = df_gp['g_c_p'] - df_gp['b_c_p']
ks_max = max(df_gp['ks'].map(lambda x: abs(x)))
iv = sum(df_gp['IV'].tolist())
df_gp_new=df_gp[['good', 'bad', 'pct_bin', 'pct_default', 'Woe', 'IV', 'ks']]
df_gp_new.columns=['good', 'bad', 'pct_bin', 'bad_rate', 'Woe', 'IV', 'ks']
return ks_max, iv, df_gp_new
def func_tt_vardescrible(train, test,writer, train_cols, tag):
train_i = train.copy()
test_i = test.copy()
varname_list = []
varks_list = []
ks_j_ = []
ks_i_ = []
iv_i_ = []
iv_j_ = []
check = []
group = []
psi_all=[]
num = 0
for i in train_cols:
print('turn to ', i)
if i in train.columns and i != 'intercept':
ks_i, iv_i, df_gp1 = cal_ks_tt(train_i, i, tag)
ks_j, iv_j, df_gp2 = cal_ks_tt(test_i, i, tag)
varname_list.append(i[:-4])
varks_list.append(abs(ks_i - ks_j))
ks_j_.append(ks_j)
ks_i_.append(ks_i)
iv_i_.append(iv_i)
iv_j_.append(iv_j)
group.append(df_gp1.shape[0])
df_gp1 = df_gp1.reset_index()
df_gp2 = df_gp2.reset_index()
df_gp1.index = df_gp1[i]
df_gp2.index = df_gp2[i]
df_describle = pd.concat([df_gp1, df_gp2], axis=1, keys=['TRAIN', 'CROSS'], sort=False)
df_describle=df_describle.reset_index(drop=True)
df_describle['PSI'] = (df_describle[('TRAIN', 'pct_bin')] - df_describle[('CROSS', 'pct_bin')]) * np.log(
df_describle[('TRAIN', 'pct_bin')] / df_describle[('CROSS', 'pct_bin')])
psi = sum([ii for ii in df_describle['PSI'] if not pd.isnull(ii)])
psi_all.append(psi)
df_describle = df_describle.reset_index(drop=True)
# df_describle = df_describle.sort_values(('TRAIN', 'Woe'))
# 我从来没有想过会出现test不单调的情况,但是它居然出现了;没办法,只能加个判定了
# ————————————判定开始————————————
test_woe = df_describle['CROSS']['Woe'].tolist()
if pd.Series(test_woe).is_monotonic_decreasing or pd.Series(test_woe).is_monotonic_increasing:
check.append(0)
else:
check.append(1)
# ————————————判定结束————————————
df_describle.to_excel(writer,'各入模变量段训练_跨时间集分布对比', startrow=num )
num += len(df_describle) + 4
test_ks = pd.DataFrame({'var': varname_list,
'ks_train': ks_i_,
'ks_test': ks_j_,
'ks_dif': varks_list,
'iv_train': iv_i_,
'iv_test': iv_j_,
'check': check,
'group': group,
'PSI': psi_all
})
ks_sort = test_ks.sort_values('ks_test', ascending=False)[[
'var', 'iv_train', 'iv_test', 'ks_train', 'ks_test', 'ks_dif', 'group', 'check','PSI']]
ks_sort.to_excel(writer, '各入模变量段训练_跨时间集指标汇总', startrow=0)
# return ks_sort<file_sep># -*- coding:utf-8 -*-
param_dic = {
#系统python路径:
'system_python_path':'D:\ProgramData\Anaconda3\python.exe',
###############d01 特征探查及分布###############
# d01_项目名
'project_name': 'data_fraud',
# d01_数据文件名
'data_file': 'zz_bcard_sample_merge_2_from1016.csv',
# d01_Y字段名
'tag': 'y_flag',
# d01_测试集比例
'test_size': 0.2,
# d01_主键
'key': 'loan_apply_no',
# d01_数据分位数
'percentiles': [0.001, 0.010, 0.025, 0.050, 0.100, 0.200, 0.300, 0.400, 0.500, 0.600, 0.700, 0.800, 0.900, 0.950,
0.975, 0.990, 0.999],
# d01_是否画箱线图
'bin_image': False,
###############d02 特征分箱##############
# d02_分箱是否添加相关性标签:
'bin_ex_corr': False,
# d02_是否输出自动分箱:
'output_auto_cut_bin': True,
# d02_是否输出不分箱:
'output_uncut_bin': False,
# d02_变量相关性系数阀值
'corr_limit': 0.8,
# d02_自动分箱最大箱数
'auto_bin_num': 5,
# d02_分箱是否单调
'mono': True,
###############d03 特征衍生##############
# d03_分箱是否添加相关性标签:
'file_input': '20190327184447__za_jr_dw_dev_hvs5123_preA_basic_info_with_city_level.csv',
# d03_输入衍生特征list
'derivate_var_list': ['age', 'usermobileonlinedd', 'certi_city_level', 'phone_city_level', ],
# d03_需衍生计算指标
'derivate_agg_list': ['sum', 'min', 'max', 'mean', 'minus', 'rate', 'std'],
# 举例两两组合衍生即n=2
'derivate_var_n': 2,
#d03_输出衍生变量数据集路径
'output_data_file': './data/data_derivated.csv',
# d03_输出衍生变量中文名路径
'output_datasource_file': './data/data_source_derivated.csv',
###############d04 模型训练##############
# d04模型训练步骤(1:初步训练 2:训练调优 3 跨时间集验证 4跨时间集单变量PSI)
'step': 1,
# d04_模型是否去相关性:
'model_ex_corr': True,
# d04_评分卡刻度-初始分(训练集整体坏好比)分数
'base_score': 500,
# d04_评分卡刻度-训练集整体坏好比的翻倍分数
'double_score': -50,
# d04_剔除变量名(默认放入Y标签和主键)
'ex_cols': ['y_flag', 'loan_apply_no', 'certi_no_md5'],
# d04_入模必要变量名
'nece_var': [
],
# d04_是否仅必要变量名入模
'is_all_necess': False,
# d04_跨时间数据文件名,默认放置data文件夹下
'cross_sample': 'zz_bcard_sample_merge_2_overtime.csv',
#d04_变量跨时间psi表现
'model_vars_psi':[]
}
<file_sep>import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
def MakeupMissingCategorical(x):
if str(x) == 'nan':
return 'Unknown'
else:
return x
def MakeupMissingNumerical(x,replacement):
if np.isnan(x):
return replacement
else:
return x
'''
第一步:文件准备
'''
foldOfData = 'H:/'
mydata = pd.read_csv(foldOfData + "还款率模型.csv",header = 0,engine ='python')
#催收还款率等于催收金额/(所欠本息+催收费用)。其中催收费用以支出形式表示
mydata['rec_rate'] = mydata.apply(lambda x: x.LP_NonPrincipalRecoverypayments /(x.AmountDelinquent-x.LP_CollectionFees), axis=1)
#还款率假如大于1,按作1处理
mydata['rec_rate'] = mydata['rec_rate'].map(lambda x: min(x,1))
#整个开发数据分为训练集、测试集2个部分
trainData, testData = train_test_split(mydata,test_size=0.4)
'''
第二步:数据预处理
'''
#由于不存在数据字典,所以只分类了一些数据
categoricalFeatures = ['CreditGrade','Term','BorrowerState','Occupation','EmploymentStatus','IsBorrowerHomeowner','CurrentlyInGroup','IncomeVerifiable']
numFeatures = ['BorrowerAPR','BorrowerRate','LenderYield','ProsperRating (numeric)','ProsperScore','ListingCategory (numeric)','EmploymentStatusDuration','CurrentCreditLines',
'OpenCreditLines','TotalCreditLinespast7years','CreditScoreRangeLower','OpenRevolvingAccounts','OpenRevolvingMonthlyPayment','InquiriesLast6Months','TotalInquiries',
'CurrentDelinquencies','DelinquenciesLast7Years','PublicRecordsLast10Years','PublicRecordsLast12Months','BankcardUtilization','TradesNeverDelinquent (percentage)',
'TradesOpenedLast6Months','DebtToIncomeRatio','LoanFirstDefaultedCycleNumber','LoanMonthsSinceOrigination','PercentFunded','Recommendations','InvestmentFromFriendsCount',
'Investors']
'''
类别型变量需要用目标变量的均值进行编码
'''
encodedFeatures = []
encodedDict = {}
for var in categoricalFeatures:
trainData[var] = trainData[var].map(MakeupMissingCategorical)
avgTarget = trainData.groupby([var])['rec_rate'].mean()
avgTarget = avgTarget.to_dict()
newVar = var + '_encoded'
trainData[newVar] = trainData[var].map(avgTarget)
encodedFeatures.append(newVar)
encodedDict[var] = avgTarget
#对数值型数据的缺失进行补缺
trainData['ProsperRating (numeric)'] = trainData['ProsperRating (numeric)'].map(lambda x: MakeupMissingNumerical(x,0))
trainData['ProsperScore'] = trainData['ProsperScore'].map(lambda x: MakeupMissingNumerical(x,0))
avgDebtToIncomeRatio = np.mean(trainData['DebtToIncomeRatio'])
trainData['DebtToIncomeRatio'] = trainData['DebtToIncomeRatio'].map(lambda x: MakeupMissingNumerical(x,avgDebtToIncomeRatio))
numFeatures2 = numFeatures + encodedFeatures
'''
第三步:调参
对基于CART的随机森林的调参,主要有:
1,树的个数
2,树的最大深度
3,内部节点最少样本数与叶节点最少样本数
4,特征个数
此外,调参过程中选择的误差函数是均值误差,5倍折叠
'''
X, y= trainData[numFeatures2],trainData['rec_rate']
param_test1 = {'n_estimators':range(60,91,5)}
gsearch1 = GridSearchCV(estimator = RandomForestRegressor(min_samples_split=50,min_samples_leaf=10,max_depth=8,max_features='sqrt' ,random_state=10),param_grid = param_test1, scoring='neg_mean_squared_error',cv=5)
gsearch1.fit(X,y)
gsearch1.best_params_, gsearch1.best_score_
best_n_estimators = gsearch1.best_params_['n_estimators']
param_test2 = {'max_depth':range(3,15), 'min_samples_split':range(10,101,10)}
gsearch2 = GridSearchCV(estimator = RandomForestRegressor(n_estimators=best_n_estimators, min_samples_leaf=10,max_features='sqrt' ,random_state=10,oob_score=True),param_grid = param_test2, scoring='neg_mean_squared_error',cv=5)
gsearch2.fit(X,y)
gsearch2.best_params_, gsearch2.best_score_
best_max_depth = gsearch2.best_params_['max_depth']
best_min_samples_split = gsearch2.best_params_['min_samples_split']
param_test3 = {'min_samples_leaf':range(1,20,2)}
gsearch3 = GridSearchCV(estimator = RandomForestRegressor(n_estimators=best_n_estimators, max_depth = best_max_depth,max_features='sqrt',min_samples_split=best_min_samples_split,random_state=10,oob_score=True),param_grid = param_test3, scoring='neg_mean_squared_error',cv=5)
gsearch3.fit(X,y)
gsearch3.best_params_, gsearch3.best_score_
best_min_samples_leaf = gsearch3.best_params_['min_samples_leaf']
numOfFeatures = len(numFeatures2)
mostSelectedFeatures = numOfFeatures/2
param_test4 = {'max_features':range(3,numOfFeatures+1)}
gsearch4 = GridSearchCV(estimator = RandomForestRegressor(n_estimators=best_n_estimators, max_depth=best_max_depth,min_samples_leaf=best_min_samples_leaf,min_samples_split=best_min_samples_split,random_state=10,oob_score=True),param_grid = param_test4, scoring='neg_mean_squared_error',cv=5)
gsearch4.fit(X,y)
gsearch4.best_params_, gsearch4.best_score_
best_max_features = gsearch4.best_params_['max_features']
#把最优参数全部获取去做随机森林拟合
cls = RandomForestRegressor(n_estimators=best_n_estimators,max_depth=best_max_depth,min_samples_leaf=best_min_samples_leaf,min_samples_split=best_min_samples_split,max_features=best_max_features,random_state=10,oob_score=True)
cls.fit(X,y)
trainData['pred'] = cls.predict(trainData[numFeatures2])
trainData['less_rr'] = trainData.apply(lambda x: int(x.pred > x.rec_rate), axis=1)
np.mean(trainData['less_rr'])
err = trainData.apply(lambda x: np.abs(x.pred - x.rec_rate), axis=1)
np.mean(err)
#随机森林评估变量重要性
importance=cls.feature_importances_
featureImportance=dict(zip(numFeatures2,importance))
featureImportance=sorted(featureImportance.items(),key=lambda x:x[1],reverse=True)
'''
第四步:在测试集上测试效果
'''
#类别型数据处理
for var in categoricalFeatures:
testData[var] = testData[var].map(MakeupMissingCategorical)
newVar = var + '_encoded'
testData[newVar] = testData[var].map(encodedDict[var])
avgnewVar = np.mean(trainData[newVar])
testData[newVar] = testData[newVar].map(lambda x: MakeupMissingNumerical(x, avgnewVar))
#连续性数据处理
testData['ProsperRating (numeric)'] = testData['ProsperRating (numeric)'].map(lambda x: MakeupMissingNumerical(x,0))
testData['ProsperScore'] = testData['ProsperScore'].map(lambda x: MakeupMissingNumerical(x,0))
testData['DebtToIncomeRatio'] = testData['DebtToIncomeRatio'].map(lambda x: MakeupMissingNumerical(x,avgDebtToIncomeRatio))
testData['pred'] = cls.predict(testData[numFeatures2])
testData['less_rr'] = testData.apply(lambda x: int(x.pred > x.rec_rate), axis=1)
np.mean(testData['less_rr'])
err = testData.apply(lambda x: np.abs(x.pred - x.rec_rate), axis=1)
np.mean(err)<file_sep>from binning.base import Binning
from binning.supervised import ChiSquareBinning
from binning.unsupervised import EqualFrequencyBinning, EqualWidthBinning, equal_frequency_binning, equal_width_binning
__all__ = [
'Binning',
'ChiSquareBinning',
'EqualWidthBinning',
'EqualFrequencyBinning',
'equal_width_binning',
'equal_frequency_binning'
]<file_sep>import pandas as pd
from collections import defaultdict
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
from sklearn.utils import is_scalar_nan
from utils import searchsorted, assign_group, map_series
class Binning(BaseEstimator, TransformerMixin):
""" Base class for all Binning functionalities,
Subclasses should overwrite the _fit and _transform method for their own purporses.
"""
def __init__(self,
cols=None,
bins=None,
encode: bool = True,
fill: int = -1):
""" bins is a dictionary mapping column names to its transformation rule. The transformation rule
can either be a list of cutoff points or a dictionary of value mapping.
If a column is specified in the `bins` argument, it will not be fitted during the `fit` method.
:param cols: A list of columns to perform binning, if set to None, perform binning on all columns.
:param encode: If set to False, the result of transform will be right cutoff point of the interval
:param fill: Used to fill in missing value.
"""
self.cols = cols
# self.set_bins is used to store all the user_specified cutoffs
self.set_bins = bins or dict()
# self.bins is used to track all the cutoff points
self.bins = None
self.encode = encode
self.fill = fill
def _fit(self, X: pd.Series, y, **fit_parmas):
""" Fit a single feature and return the cutoff points or None,
If None is returned, that column will not be binned.
"""
raise NotImplementedError
def _transform(self, X: pd.Series, y=None):
""" Transform a single feature which has been fitted, aka the _fit method
returns cutoff points rather than None
"""
col_name = X.name
rule = self.bins[col_name]
binned = assign_group(X, rule)
if self.encode:
return searchsorted(rule, binned, self.fill)
else:
return binned
def fit(self, X: pd.DataFrame, y=None, **fit_params):
"""
:param X: Pandas DataFrame with shape (n_sample, n_feature)
:param y: a label column with shape (n_sample, )
"""
cols = self.cols or X.columns.tolist()
self.bins = dict()
for col in cols:
# use the user specified cutoff point
if col in self.set_bins:
if isinstance(self.set_bins[col], list):
self.bins[col] = sorted(self.set_bins[col])
else:
self.bins[col] = self.set_bins[col]
continue
cutoff = self._fit(X[col], y)
if cutoff is not None:
# save the sorted cutoff points
self.bins[col] = sorted(cutoff)
else:
# save a mapping from value to encoding value (starting from 1)
self.bins[col] = {v: (k+1) for k, v in enumerate(X[col].unique()) \
if not is_scalar_nan(v)}
return self
def transform(self, X: pd.DataFrame, y=None):
if self.bins is None:
raise NotFittedError('This {} is not fitted. Call the fit method first.'.format(self.__class__.__name__))
x = X.copy()
for col in self.cols or X.columns:
if col not in self.bins:
raise ValueError('{} was not seen during the fit process'.format(col))
else:
if isinstance(self.bins[col], list):
# rule is the cutoff points
x[col] = self._transform(x[col])
else:
# rule is the mapping, set any unseen categories to 0
mapping = self.bins[col]
x[col] = map_series(x[col], mapping, 0, self.fill)
return x
def get_interval_mapping(self, col_name: str):
""" Get the mapping from encoded value to its corresponding group. """
if self.bins is None:
raise NotFittedError('This {} is not fitted. Call the fit method first.'.format(self.__class__.__name__))
if col_name not in self.bins:
raise ValueError('Column {} was not seen during the fit process'.format(col_name))
rule = self.bins[col_name]
if isinstance(rule, list):
length = len(rule)
interval = enumerate([rule[i:i + 2] for i in range(length - 1)])
# the first interval is close on both ends
interval = ['[' + ', '.join(map(str, j)) + ']' if i == 0 else
'(' + ', '.join(map(str, j)) + ']'
for i, j in interval]
interval = ['(-inf, {})'.format(min(rule))] + interval + ['({}, inf)'.format(max(rule))]
mapping = dict(enumerate(interval))
mapping[self.fill] = 'MISSING'
return mapping
else:
mapping = defaultdict(list)
for k, v in rule.items():
mapping[v].append(k)
mapping = {k: '[' + ', '.join(map(str, v)) + ']' for k, v in mapping.items()}
mapping[self.fill] = 'MISSING'
mapping[0] = 'UNSEEN'
return mapping<file_sep># -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import re
import math
import time
import itertools
from itertools import combinations
from numpy import array
from math import sqrt
from multiprocessing import Pool
import tool
def get_max_ks(date_df, start, end, rate, bad_name, good_name):
ks = ''
if end == start:
return ks
bad = date_df.loc[start:end, bad_name]
good = date_df.loc[start:end, good_name]
bad_good_cum = list(abs(np.cumsum(bad / sum(bad)) - np.cumsum(good / sum(good))))
if bad_good_cum:
ks = start + bad_good_cum.index(max(bad_good_cum))
return ks
def cut_while_fun(start, end, piece, date_df, rate, bad_name, good_name, counts):
'''
:param start: 起始位置0
:param end: 终止位置
:param piece: 起始切分组
:param date_df: 数据集
:param rate: 最小分组占比
:param bad_name: Y标签1对应列名
:param good_name: Y标签0对应列名
:param counts: 默认从1计数
:return:
'''
point_all = []
if counts >= piece or len(point_all) >= pow(2, piece - 1):
return []
ks_point = get_max_ks(date_df, start, end, rate, bad_name, good_name)
if ks_point:
if ks_point != '':
t_up = cut_while_fun(start, ks_point, piece, date_df, rate, bad_name, good_name, counts + 1)
else:
t_up = []
t_down = cut_while_fun(ks_point + 1, end, piece, date_df, rate, bad_name, good_name, counts + 1)
else:
t_up = []
t_down = []
point_all = t_up + [ks_point] + t_down
return point_all
def ks_auto(date_df, piece, rate, bad_name, good_name):
t_list = list(set(cut_while_fun(0, len(date_df) - 1, piece - 1, date_df, rate, bad_name, good_name, 1)))
# py2
# ks_point_all = [0] + filter(lambda x: x != '', t_list) + [len(date_df) - 1]
# py3
ks_point_all = [0] + list(filter(lambda x: x != '', t_list)) + [len(date_df) - 1]
return ks_point_all
def get_combine(t_list, date_df, piece):
t1 = 0
t2 = len(date_df) - 1
list0 = t_list[1:len(t_list) - 1]
combine = []
if len(t_list) - 2 < piece:
c = len(t_list) - 2
else:
c = piece - 1
list1 = list(itertools.combinations(list0, c))
if list1:
combine = map(lambda x: sorted(x + (t1 - 1, t2)), list1)
return combine
def cal_iv(date_df, items, bad_name, good_name, rate, total_all, mono=True):
iv0 = 0
total_rate = [sum(date_df.ix[x[0]:x[1], bad_name] + date_df.ix[x[0]:x[1], good_name]) * 1.0 / total_all for x in
items]
if [k for k in total_rate if k < rate]:
return 0
bad0 = array(list(map(lambda x: sum(date_df.ix[x[0]:x[1], bad_name]), items)))
good0 = array(list(map(lambda x: sum(date_df.ix[x[0]:x[1], good_name]), items)))
bad_rate0 = bad0 * 1.0 / (bad0 + good0)
if 0 in bad0 or 0 in good0:
return 0
good_per0 = good0 * 1.0 / sum(date_df[good_name])
bad_per0 = bad0 * 1.0 / sum(date_df[bad_name])
woe0 = list(map(lambda x: math.log(x, math.e), good_per0 / bad_per0))
if mono:
if sorted(woe0, reverse=False) == list(woe0) and sorted(bad_rate0, reverse=True) == list(bad_rate0):
iv0 = sum(woe0 * (good_per0 - bad_per0))
elif sorted(woe0, reverse=True) == list(woe0) and sorted(bad_rate0, reverse=False) == list(bad_rate0):
iv0 = sum(woe0 * (good_per0 - bad_per0))
else:
iv0 = sum(woe0 * (good_per0 - bad_per0))
return iv0
def choose_best_combine(date_df, combine, bad_name, good_name, rate, total_all, mono=True):
z = [0] * len(combine)
for i in range(len(combine)):
item = combine[i]
z[i] = list(zip(map(lambda x: x + 1, item[0:len(item) - 1]), item[1:]))
iv_list = list(map(lambda x: cal_iv(date_df, x, bad_name, good_name, rate, total_all, mono=mono), z))
iv_max = max(iv_list)
if iv_max == 0:
return ''
index_max = iv_list.index(iv_max)
combine_max = z[index_max]
return combine_max
def verify_woe(x):
if re.match('^\-?\\d*\.?\d+$', str(x)):
return x
else:
return 0
def best_df(date_df, items, na_df, factor_name, bad_name, good_name, total_all, good_all, bad_all, var_val_type):
df0 = pd.DataFrame()
if items:
if var_val_type == 'number':
right_max = list(map(lambda x: str(date_df.ix[x[1], factor_name]), items))
piece0_old = list(map(
lambda x: '(' + str(date_df.ix[x[0], factor_name]) + ',' + str(date_df.ix[x[1], factor_name]) + ')',
items))
# print(piece0_old)
piece0_new = tool.get_bin_cate(right_max)
piece0 = piece0_new
# print(piece0_new)
else:
piece0 = list(map(
lambda x: '(' + ','.join(date_df.ix[x[0]:x[1], factor_name]) + ')',
items))
bad0 = list(map(lambda x: sum(date_df.ix[x[0]:x[1], bad_name]), items))
good0 = list(map(lambda x: sum(date_df.ix[x[0]:x[1], good_name]), items))
if len(na_df) > 0:
piece0 = array(
list(piece0) + list(map(lambda x: '(' + str(x) + ',' + str(x) + ')', list(na_df[factor_name]))))
bad0 = array(list(bad0) + list(na_df[bad_name]))
good0 = array(list(good0) + list(na_df[good_name]))
else:
piece0 = array(list(piece0))
bad0 = array(list(bad0))
good0 = array(list(good0))
total0 = bad0 + good0
total_per0 = total0 * 1.0 / total_all
bad_rate0 = bad0 * 1.0 / total0
good_rate0 = 1 - bad_rate0
good_per0 = good0 * 1.0 / good_all
bad_per0 = bad0 * 1.0 / bad_all
df0 = pd.DataFrame(
list(zip(piece0, total0, bad0, good0, total_per0, bad_rate0, good_rate0, good_per0, bad_per0)),
columns=[factor_name, 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate', 'Good_Rate',
'Good_Pcnt', 'Bad_Pcnt'])
df0 = df0.sort_values(by='Bad_Rate', ascending=False)
df0.index = range(len(df0))
bad_per0 = array(list(df0['Bad_Pcnt']))
good_per0 = array(list(df0['Good_Pcnt']))
bad_rate0 = array(list(df0['Bad_Rate']))
good_rate0 = array(list(df0['Good_Rate']))
bad_cum = np.cumsum(bad_per0)
good_cum = np.cumsum(good_per0)
woe0 = list(map(lambda x: math.log(x, math.e), good_per0 / bad_per0))
print(woe0)
if 'inf' in str(woe0):
woe0 = list(map(lambda x: verify_woe(x), woe0))
print(woe0)
iv0 = woe0 * (good_per0 - bad_per0)
gini = 1 - pow(good_rate0, 2) - pow(bad_rate0, 2)
df0['Bad_Cum'] = bad_cum
df0['Good_Cum'] = good_cum
df0["Woe"] = woe0
df0["IV"] = iv0
df0['Gini'] = gini
df0['KS'] = abs(df0['Good_Cum'] - df0['Bad_Cum'])
return df0
def all_information(date_df, na_df, piece, rate, factor_name, bad_name, good_name, total_all, good_all, bad_all,
var_val_type, mono=True):
'''
:param date_df:非异常值数据
:param na_df 空值数据
:param piece:切割组数
:param rate:最小分组比例
:param factor_name:变量名
:param bad_name:坏的列名
:param good_name:好的列名
:param total_all:总样本数
:param good_all:好的总样本数
:param bad_all:坏的总样本数
:return:
'''
p_sort = range(piece + 1)
p_sort = [i for i in p_sort]
p_sort.sort(reverse=True)
t_list = ks_auto(date_df, piece, rate, bad_name, good_name)
if not t_list:
df1 = pd.DataFrame()
print('Warning: this data cannot get bins or the bins does not satisfy monotonicity')
return df1
df1 = pd.DataFrame()
for c in p_sort[:piece - 1]:
combine = list(get_combine(t_list, date_df, c))
best_combine = choose_best_combine(date_df, combine, bad_name, good_name, rate, total_all, mono=mono)
df1 = best_df(date_df, best_combine, na_df, factor_name, bad_name, good_name, total_all, good_all, bad_all,
var_val_type)
if len(df1) != 0:
gini = sum(df1['Gini'] * df1['Total_Num'] / sum(df1['Total_Num']))
print('piece_count:', str(len(df1)))
print('IV_All_Max:', str(sum(df1['IV'])))
print('Best_KS:', str(max(df1['KS'])))
print('Gini_index:', str(gini))
print(df1)
return df1
if len(df1) == 0:
print('Warning: this data cannot get bins or the bins does not satisfy monotonicity')
return df1
def verify_factor(x,value_type=[]):
if x in ['NA', 'NAN', '', ' ', 'MISSING', 'NONE', 'NULL']:
return 'NAN'
if value_type=='number':
if re.match('^\-?\d*\.?\d+$', x):
x = float(x)
return x
def path_df(path, sep, factor_name):
data = pd.read_csv(path, sep=sep)
data[factor_name] = data[factor_name].astype(str).map(lambda x: x.upper())
data[factor_name] = data[factor_name].apply(lambda x: re.sub(' ', 'MISSING', x))
return data
def verify_df_multiple(date_df, factor_name, total_name, bad_name, good_name):
"""
:param date_df: factor_name,....
:return: factor_name,good_name,bad_name
"""
date_df = date_df.fillna(0)
cols = date_df.columns
if total_name in cols:
date_df = date_df[date_df[total_name] != 0]
if bad_name in cols and good_name in cols:
date_df_check = date_df[date_df[good_name] + date_df[bad_name] - date_df[total_name] != 0]
if len(date_df_check) > 0:
date_df = pd.DataFrame()
print('Error: total amounts is not equal to the sum of bad & good amounts')
print(date_df_check)
return date_df
elif bad_name in cols:
date_df_check = date_df[date_df[total_name] - date_df[bad_name] < 0]
if len(date_df_check) > 0:
date_df = pd.DataFrame()
print('Error: total amounts is smaller than bad amounts')
print(date_df_check)
return date_df
date_df[good_name] = date_df[total_name] - date_df[bad_name]
elif good_name in cols:
date_df_check = date_df[date_df[total_name] - date_df[good_name] < 0]
if len(date_df_check) > 0:
date_df = pd.DataFrame()
print('Error: total amounts is smaller than good amounts')
print(date_df_check)
return date_df
date_df[bad_name] = date_df[total_name] - date_df[good_name]
else:
print('Error: lack of bad or good data')
date_df = pd.DataFrame()
return date_df
del date_df[total_name]
elif bad_name not in cols:
print('Error: lack of bad data')
date_df = pd.DataFrame()
return date_df
elif good_name not in cols:
print('Error: lack of good data')
date_df = pd.DataFrame()
return date_df
date_df[good_name] = date_df[good_name].astype(int)
date_df[bad_name] = date_df[bad_name].astype(int)
date_df = date_df[date_df[bad_name] + date_df[good_name] != 0]
date_df[factor_name] = date_df[factor_name].map(verify_factor)
date_df = date_df.sort_values(by=[factor_name], ascending=True)
date_df[factor_name] = date_df[factor_name].astype(str)
if len(date_df[factor_name]) != len(set(date_df[factor_name])):
df_bad = date_df.groupby(factor_name)[bad_name].agg([(bad_name, 'sum')]).reset_index()
df_good = date_df.groupby(factor_name)[good_name].agg([(good_name, 'sum')]).reset_index()
good_dict = dict(zip(df_good[factor_name], df_good[good_name]))
df_bad[good_name] = df_bad[factor_name].map(good_dict)
df_bad.index = range(len(df_bad))
date_df = df_bad
return date_df
def verify_df_two(data_df, flag_name, factor_name, good_name, bad_name,value_type):
"""
:param data_df, factor_name, flag_name
:return: factor_name,good_name,bad_name
预处理:将df_按照flag(0-1)groupby,并按照var_value排序
"""
data_df = data_df[-pd.isnull(data_df[flag_name])]
if len(data_df) == 0:
print('Error: the data is wrong')
return data_df
check = data_df[data_df[flag_name] > 1]
if len(check) != 0:
print('Error: there exits the number bigger than one in the data')
data_df = pd.DataFrame()
return data_df
if flag_name != '':
try:
data_df[flag_name] = data_df[flag_name].astype(int)
except:
print('Error: the data is wrong')
data_df = pd.DataFrame()
return data_df
data_df = data_df[flag_name].groupby(
[data_df[factor_name], data_df[flag_name]]).count().unstack().reset_index().fillna(0)
data_df.columns = [factor_name, good_name, bad_name]
data_df[factor_name] = data_df[factor_name].apply(lambda x:verify_factor(x,value_type))
# data_df_1=data_df[data_df[factor_name].apply(lambda x: str(x).find('NAN')>=0 or str(x).find('E')>=0)]
# data_df_2=data_df[~data_df[factor_name].apply(lambda x: str(x).find('NAN')>=0 or str(x).find('E')>=0)]
# data_df_2 = data_df_2.sort_values(by=[factor_name], ascending=True)
# data_df=pd.concat([data_df_1,data_df_2])
data_df.index = range(len(data_df))
data_df[factor_name] = data_df[factor_name].astype(str)
return data_df
def universal_df(data, flag_name, factor_name, total_name, bad_name, good_name,value_type):
if flag_name != '':
data = data[[factor_name, flag_name]]
data = verify_df_two(data, flag_name, factor_name, good_name, bad_name,value_type)
else:
data = verify_df_multiple(data, factor_name, total_name, bad_name, good_name,value_type)
return data
def Best_KS_Bin(path='', data=pd.DataFrame(), sep=',', flag_name='', factor_name='name', total_name='total',
bad_name='bad', good_name='good', bin_num=5, rate=0.05, not_in_list=[], value_type=True,
var_type='number', mono=True):
"""
:param flag_name:Y标签
:param factor_name: 变量名
:param total_name:
:param bad_name: bad
:param good_name: good
:param bin_num:切割组数,默认5
:param rate:分组占比不得小于
:param not_in_list:['NaN', '-1.0', '', '-1']
:param value_type: True is numerical; False is nominal
"""
# none_list = ['NA', 'NAN', '', ' ', 'MISSING', 'NONE', 'NULL']
if path != '':
# 若直接调用分箱则输入数据路径
data = path_df(path, sep, factor_name)
elif len(data) == 0:
print('Error: there is no data')
return data
data = data.copy()
data[factor_name] = data[factor_name].apply(lambda x: str(x).upper().replace(',', '_'))
data = universal_df(data, flag_name, factor_name, total_name, bad_name, good_name,value_type)
if len(data) == 0:
return data
good_all = sum(data[good_name])
bad_all = sum(data[bad_name])
total_all = good_all + bad_all
if not_in_list:
# 空值分组
not_name = [str(k).upper() for k in not_in_list]
# for n0 in none_list:
# print (n0)
# if n0 in not_name:
# not_name += ['NAN'] # todo
# print(not_name)
# break
na_df = data[data[factor_name].isin(not_name)]
if (0 in na_df[good_name]) or (0 in na_df[bad_name]):
not_value = list(
set(list(na_df[na_df[good_name] == 0][factor_name]) + list(na_df[na_df[bad_name] == 0][factor_name])))
na_df = na_df.drop(na_df[na_df[factor_name].isin(not_value)].index)
na_df.index = range(len(na_df))
not_list = list(set(na_df[factor_name]))
date_df = data[-data[factor_name].isin(not_list)]
else:
na_df = pd.DataFrame()
date_df = data
if len(date_df) == 0:
print('Error: the data is wrong.')
data = pd.DataFrame()
return data
if value_type:
date_df = date_df.copy()
if var_type != 'str':
date_df[factor_name] = date_df[factor_name].apply(lambda x:verify_factor(x,var_type))
type_len = set([type(k) for k in list(date_df[factor_name])])
if len(type_len) > 1:
str_df = date_df[date_df[factor_name].map(lambda x: type(x) == str)]
number_df = date_df[date_df[factor_name].map(lambda x: type(x) == float)]
number_df = number_df.sort_values(by=factor_name)
str_df = str_df.sort_values(by=factor_name)
date_df = str_df.append(number_df)
else:
date_df = date_df.sort_values(by=factor_name)
else:
date_df['bad_rate'] = date_df[bad_name] * 1.0 / (date_df[good_name] + date_df[bad_name])
date_df = date_df.sort_values(by=['bad_rate', factor_name], ascending=False)
date_df[factor_name] = date_df[factor_name].astype(str) # todo
date_df.index = range(len(date_df))
# date_df.to_csv('./test.csv')
# date_df.to_csv('11.csv', index=False)
# print(date_df)
# ks分箱
bin_df = all_information(date_df, na_df, bin_num, rate, factor_name, bad_name, good_name, total_all, good_all,
bad_all, var_type, mono=mono)
return bin_df
# df_1=Best_KS_Bin(rule,flag_name='c.is_overdue',factor_name='callintotdsstsumj150d')
# ,not_in_list=['NaN','-1.0','-2.0'])
# df_1 = Best_KS_Bin(data=rule[['callintotdsstsumj150d', 'c.is_overdue']], flag_name='c.is_overdue',
# factor_name='callintotdsstsumj150d', not_in_list=['NaN', '-1.0', '', '-1'])
def find_another_x(x, bin_dict):
cc = {}
for i in bin_dict.keys():
if i not in ['(-1.0,-1.0)', '(NAN,NAN)']:
cc[float(i.split(',')[0][1:])] = i
dd = []
for i in cc.keys():
if i < x:
dd.append(i)
if dd == []:
nd_key = min(cc.keys())
else:
nd_key = max(dd)
bin_i = cc[nd_key]
return bin_i
def assign_woe(x, dics, var_name,str_vars,path):
'''
:param x: 变量值
:param dics:输入所需的变量woe_dic
:param var_name: 变量名
:return: 此函数用于训练集匹配woe,输入变量值,返回该变量对应的woe值;注意:若不采用BEST_KS的时候,需将区间改为左开右闭;
'''
if var_name in str_vars:
x = str(x).upper().replace(',', '_')
dic = dics[var_name]
for i in dic.keys():
# if 'NAN' in str(i) and str(x) in ['-999', '-999.0', '', '-1.0', '-1', 'nan']:
if 'NAN' in str(i) and str(x) in [ 'NAN','nan']:
y = dic[i]
bin = i
return y, bin
# if i in ['(-1,-1)', '(-1.0,-1.0)', '[-1,-1]'] and x == -1:
# y = dic[i]
# bin = i
else:
if var_name in str_vars:
if x in set(i[1:-1].split(',')):
y = dic[i]
bin = i
else:
try:
bin_num_1 = float(str(i).split(',')[0][1:].replace('(',''))
bin_num_2 = float(str(i).split(',')[1][:-1].replace(']',''))
# from interval import Interval
# zoom_bin = Interval(bin_num_1, bin_num_2, lower_closed=False)
# if float(x) in zoom_bin:
# y = str(dic[i])
# bin = i
if float(bin_num_1) < float(x) <= float(bin_num_2):
y = str(dic[i])
bin = i
except:
y = np.mean(list(dic.values()))
bin = '(-999,-999)'
error_str = ','.join([var_name, str(x), 'not in range'])
f = open(path + "_var_error_value.csv", "a")
f.write(error_str + '\n')
f.close()
try:
return y, bin
except:
# print 'try to save it '
if var_name not in str_vars:
bin = find_another_x(x, dic)
y = dic[bin]
else:
y = np.mean(list(dic.values()))
bin = '(-999,-999)'
error_str = ','.join([var_name, str(x), 'not in range'])
f = open(path + "_var_error_value.csv", "a")
f.write(error_str + '\n')
f.close()
return float(y), bin
def apply_woe(data, woe_dic, str_vars, key, tag, cols=None,path=''):
'''
:param data: 原始数据['key','tag']
:param woe_dic:
:param str_vars:字符型特征list
:return:m_data:注意:此m_data种包含所有变量,如只需入参变量,需后期筛选
'''
if cols:
vars = cols
else:
vars = data.columns.tolist()
vars_ = vars[:]
vars_.extend([key, tag])
nd_data = data[[key, tag]]
# data_1 = data.fillna(-1)
data_1=data.copy()
nd_datas = nd_data.copy()
error_var=[]
for i in vars:
if i in woe_dic.keys():
nd_datas[i + '_woe'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i,str_vars,path)[0])
nd_datas[i + '_bin'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i,str_vars,path)[1])
nd_datas[i] = data_1[i][:]
# for i in vars:
# ###
# try:
# if i in woe_dic.keys():
# nd_datas[i + '_woe'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i,str_vars,path)[0])
# nd_datas[i + '_bin'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i,str_vars,path)[1])
# nd_datas[i] = data_1[i][:]
# except Exception:
# error_var.append(i)
# print (i, 'error mapped')
###
# try:
# if i in woe_dic.keys():
# nd_datas[i + '_woe'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i)[0])
# nd_datas[i + '_bin'] = data_1[i].map(lambda x: assign_woe(x, woe_dic, i)[1])
# nd_datas[i] = data_1[i][:]
# except Exception:
# print (i, 'error mapped')
# if error_var:
# pd.DataFrame(error_var).to_csv(path+'_apply_woe_error_vars.csv',index=False,encoding='gbk')
return nd_datas
def filter_by_corr(df_, series_, nec_vars=[], corr_limit=0.8):
"""
df_: 包含WOE的数据(train)
series_: Info表的var列,需要按优先级提前排序,默认IV
corr_limit: 筛选的相关性阈值
"""
series_ = [i for i in series_ if i not in nec_vars]
series_ = [i + "_woe" for i in series_
if i + "_woe" in df_.columns]
nec_vars = [i + "_woe" for i in nec_vars if i + "_woe" in df_.columns]
drop_set, var_set = set(), set(series_)
for i in series_:
if i in var_set:
var_set.remove(i)
if i not in drop_set:
drop_set |= {v for v in var_set if np.corrcoef(
df_[i].values.astype(float), df_[v].values.astype(float))[0, 1] > corr_limit}
var_set -= drop_set
return list(set([i for i in series_ if i not in drop_set]) | set(nec_vars))
def func_good(x):
if x == 1:
y = 0
else:
y = 1
return y
def func_bad(x):
if x == 0:
y = 0
else:
y = 1
return y
def cal_ks_tt(df_rs, bin, tag):
df_rs.ix[:, 'good'] = df_rs[tag].map(lambda x: func_good(x))
df_rs.ix[:, 'bad'] = df_rs[tag].map(lambda x: func_bad(x))
df_gp = df_rs.groupby([bin])['good', 'bad'].sum()
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp.ix[:, 'bad_cnt'] = bad_cnt
df_gp.ix[:, 'good_cnt'] = good_cnt
df_gp['pct_bin'] = (df_gp['good'] + df_gp['bad']) / (bad_sum + good_sum)
df_gp['pct_default'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp['bad_pct'] = df_gp['bad'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp['good_pct'] = df_gp['good'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp['Woe'] = [0 if 'inf' in str(ii) else ii for ii in np.log(df_gp['good_pct'] / df_gp['bad_pct'])]
df_gp['IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
df_gp.ix[:, 'b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'ks'] = df_gp['g_c_p'] - df_gp['b_c_p']
ks_max = max(df_gp['ks'].map(lambda x: abs(x)))
iv = sum(df_gp['IV'].tolist())
df_gp_new=df_gp[['good', 'bad', 'pct_bin', 'pct_default', 'Woe', 'IV', 'ks']]
df_gp_new.columns=['good', 'bad', 'pct_bin', 'bad_rate', 'Woe', 'IV', 'ks']
return ks_max, iv, df_gp_new
def func_tt_vardescrible(train, test, train_cols, save_path, tag, file_tag: str):
path_ = save_path
from pandas import ExcelWriter
writer = ExcelWriter(path_ + '_train_test_compare_%s.xlsx' % file_tag)
train_i = train.copy()
test_i = test.copy()
varname_list = []
varks_list = []
ks_j_ = []
ks_i_ = []
iv_i_ = []
iv_j_ = []
check = []
group = []
psi_all=[]
num = 0
for i in train_cols:
print('turn to ', i)
if i in train.columns and i != 'intercept':
ks_i, iv_i, df_gp1 = cal_ks_tt(train_i, i, tag)
ks_j, iv_j, df_gp2 = cal_ks_tt(test_i, i, tag)
varname_list.append(i[:-4])
varks_list.append(abs(ks_i - ks_j))
ks_j_.append(ks_j)
ks_i_.append(ks_i)
iv_i_.append(iv_i)
iv_j_.append(iv_j)
group.append(df_gp1.shape[0])
df_gp1 = df_gp1.reset_index()
df_gp2 = df_gp2.reset_index()
df_gp1.index = df_gp1[i]
df_gp2.index = df_gp2[i]
df_describle = pd.concat([df_gp1, df_gp2], axis=1, keys=['TRAIN', 'CROSS'], sort=False)
df_describle=df_describle.reset_index(drop=True)
df_describle['PSI'] = (df_describle[('TRAIN', 'pct_bin')] - df_describle[('CROSS', 'pct_bin')]) * np.log(
df_describle[('TRAIN', 'pct_bin')] / df_describle[('CROSS', 'pct_bin')])
psi = sum([ii for ii in df_describle['PSI'] if not pd.isnull(ii)])
psi_all.append(psi)
df_describle = df_describle.reset_index(drop=True)
# df_describle = df_describle.sort_values(('TRAIN', 'Woe'))
# 我从来没有想过会出现test不单调的情况,但是它居然出现了;没办法,只能加个判定了
# ————————————判定开始————————————
test_woe = df_describle['TEST']['Woe'].tolist()
if pd.Series(test_woe).is_monotonic_decreasing or pd.Series(test_woe).is_monotonic_increasing:
check.append(0)
else:
check.append(1)
# ————————————判定结束————————————
df_describle.to_excel(writer,'var_details', startrow=num )
num += len(df_describle) + 4
test_ks = pd.DataFrame({'var': varname_list,
'ks_train': ks_i_,
'ks_test': ks_j_,
'ks_dif': varks_list,
'iv_train': iv_i_,
'iv_test': iv_j_,
'check': check,
'group': group,
'PSI': psi_all
})
ks_sort = test_ks.sort_values('ks_test', ascending=False)[[
'var', 'iv_train', 'iv_test', 'ks_train', 'ks_test', 'ks_dif', 'group', 'check','PSI']]
ks_sort.to_excel(writer, 'summary', startrow=0)
writer.save()
# return ks_sort
<file_sep># -*- coding:utf-8 -*-
import os
import d00_param
import imp
imp.reload(d00_param)
task_dict = {1: "d01_read_data.py", 2: "d02_woe_bin.py", 3: "d03_var_derivation.py", 4: "d04_modeling.py"}
def ExecuteFunction(py_path,task_list):
if task_list:
if 1 in task_list:
run_file = task_dict[1]
os.system(py_path + " " + run_file)
if 2 in task_list:
run_file = task_dict[2]
os.system(py_path + " " + run_file)
if 3 in task_list:
run_file = task_dict[3]
os.system(py_path + " " + run_file)
if 4 in task_list:
run_file = task_dict[4]
os.system(py_path + " " + run_file)
if __name__ == "__main__":
# python系统路径
param_dic = d00_param.param_dic
system_python_path = param_dic['system_python_path']
# 执行文件列表 1: "d01_read_data.py", 2: "d02_woe_bin.py", 3: "d03_var_derivation.py", 4: "d04_modeling.py"
task_list = [1,2,4]
ExecuteFunction(system_python_path, task_list)
<file_sep># -*- coding:utf-8 -*-
import tool
import pandas as pd
import d00_param
import imp
imp.reload(d00_param)
import pickle
import numpy as np
from modeling.stepwise import func_sort_col, func_stepwise_1
from modeling.cal_ks_auc_score import cal_ks_test, func_report, gb_add_woe, func_tt_vardescrible
import time
from sklearn.externals import joblib
from binning.best_ks_3 import apply_woe, filter_by_corr
from tool import get_bin
import os
def model(model_ex_corr=True):
start_time = time.time()
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
path_ = tool.prepare_path(project_name, 'd04_')
tag = param_dic['tag']
key = param_dic['key']
corr_limit = param_dic['corr_limit']
Xpath_ = tool.prepare_path(project_name, 'd02_')
info = pd.read_excel(Xpath_ + '_info.xlsx', sheet_name='特征IV汇总')
new_info = info[[u'特征简称', u'特征中文名', 'IV', u'覆盖率']]
new_info_dict = new_info.set_index(u'特征简称').to_dict('index')
vars = info.sort_values('IV', ascending=False)[:3000][u'特征简称'].tolist()
fin_vars = vars
# fin_vars = ['register_channel_name']
fin_vars.extend([key, tag])
if model_ex_corr and u'是否因超过共线性阀值剔除' in list(info.columns):
m_data_train = tool.read_file('./data/' + project_name + '_m_data_train.pkl')
m_data_test = tool.read_file('./data/' + project_name + '_m_data_test.pkl')
nd_vars_woe = (info[info['是否因超过共线性阀值剔除'] == 0]['特征简称'] + '_woe').tolist()
elif u'是否因超过共线性阀值剔除' in list(info.columns):
m_data_train = tool.read_file('./data/' + project_name + '_m_data_train.pkl')
m_data_test = tool.read_file('./data/' + project_name + '_m_data_test.pkl')
nd_vars_woe = (info['特征简称'] + '_woe').tolist()
elif model_ex_corr:
f = open(Xpath_ + '_vars_woe_bin_dic.pkl', "rb")
dic_woe = pickle.load(f)
df_train = tool.read_file('./data/' + project_name + '_df_train.pkl')
df_test = tool.read_file('./data/' + project_name + '_df_test.pkl')
print(10 * '*' + 'start apply woe.' + 10 * '*')
m_data_train = apply_woe(df_train[fin_vars], dic_woe, str_vars, key, tag, path=path_)
m_data_test = apply_woe(df_test[fin_vars], dic_woe, str_vars, key, tag, path=path_)
print(10 * '*' + 'finish apply woe.' + 10 * '*')
nd_vars_woe = filter_by_corr(m_data_train, fin_vars, nec_vars=[], corr_limit=corr_limit)
for i in nd_vars_woe:
m_data_train[i] = m_data_train[i].astype(float)
m_data_test[i] = m_data_test[i].astype(float)
m_data_train.to_pickle('./data/' + project_name + '_m_data_train_bin.pkl')
m_data_train = m_data_train[[ii for ii in m_data_train if ii[-4:] != '_bin']]
m_data_test = m_data_test[[ii for ii in m_data_train if ii[-4:] != '_bin']]
m_data_train.to_pickle('./data/' + project_name + '_m_data_train.pkl')
m_data_test.to_pickle('./data/' + project_name + '_m_data_test.pkl')
print(10 * '*' + 'finish vars check corr')
sort_vars = func_sort_col(nd_vars_woe, m_data_train, tag)[1]
train_cols, result, vars_dic, ks_df, error_var, odds, A, B = func_stepwise_1(sort_vars, m_data_train, tag,
pmml_btn=False, base_score=base_score,
double_score=double_score)
# 保存模型
joblib.dump(result, path_ + '_fin.model')
# 加载模型
# RF = joblib.load('rf.model')
# df_gp_uncut, df_gp_cut, df_gp_qcut, ks_df, p, df_rs_score = cal_ks_test(result, m_data_test, tag)
df_score = func_report(m_data_train, result, tag, base_score=base_score, double_score=double_score, save_path=path_,
test=m_data_test, info=None, odds=odds, score_detail_btn=False, data_dic=new_info_dict)
root_path = path_.replace('d04_' + project_name, '')
error_file = [ii for ii in os.listdir(root_path) if ii.find('_var_error_value.csv') >= 0]
if error_file:
for ii in error_file:
df = tool.read_file(root_path + ii, header=-1)
df.columns = ['var_name', 'value', 'flag']
df.drop_duplicates(inplace=True)
df.to_csv(root_path + ii, index=False)
print(10 * '*' + '存在特征未匹配到分箱请查看文件%s' % root_path + ii + 10 * '*')
df_score = df_score[[key, tag, 'score']]
df_score['score_bin'] = df_score['score'].apply(lambda x: get_bin(x, score_right_list))
df_score.to_csv(path_ + '_modeling_score.csv', index=False)
print(10 * '*' + 'finish logstic modeling')
print('spend times:', time.time() - start_time)
def model_tune(tune_del_vars=[], tune_nec_vars=[], is_all_necess=False, score_right_list=[]):
start_time = time.time()
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
path_ = tool.prepare_path(project_name, 'd04_')
tag = param_dic['tag']
key = param_dic['key']
corr_limit = param_dic['corr_limit']
Xpath_ = tool.prepare_path(project_name, 'd02_')
info = pd.read_excel(Xpath_ + '_info.xlsx', sheet_name='特征IV汇总')
new_info = info[[u'特征简称', u'特征中文名', 'IV', u'覆盖率']]
new_info_dict = new_info.set_index(u'特征简称').to_dict('index')
vars = info.sort_values('IV', ascending=False)[:3000][u'特征简称'].tolist()
m_data_train = tool.read_file('./data/' + project_name + '_m_data_train.pkl')
m_data_test = tool.read_file('./data/' + project_name + '_m_data_test.pkl')
if is_all_necess:
fin_vars = tune_nec_vars
nd_vars_woe = [i + "_woe" for i in fin_vars
if i + "_woe" in m_data_train.columns]
else:
fin_vars = filter(lambda x: x not in tune_del_vars, vars)
if model_ex_corr:
nd_vars_woe = filter_by_corr(m_data_train, fin_vars, nec_vars=tune_nec_vars, corr_limit=corr_limit)
else:
nd_vars_woe = [ii + "_woe" for ii in fin_vars if ii + "_woe" in m_data_train.columns]
for i in nd_vars_woe:
m_data_train[i] = m_data_train[i].astype(float)
m_data_test[i] = m_data_test[i].astype(float)
print(10 * '*' + 'finish vars check corr')
sort_vars = func_sort_col(nd_vars_woe, m_data_train, tag)[1]
train_cols, result, vars_dic, ks_df, error_var, odds, A, B = func_stepwise_1(sort_vars, m_data_train, tag,
pmml_btn=False, base_score=base_score,
double_score=double_score,
nec_vars=tune_nec_vars)
# 保存模型
joblib.dump(result, path_ + '_fin.model')
df_score = func_report(m_data_train, result, tag, base_score=base_score, double_score=double_score, save_path=path_,
test=m_data_test, info=None, odds=odds, score_detail_btn=False, data_dic=new_info_dict)
df_score = df_score[[key, tag, 'score']]
df_score['score_bin'] = df_score['score'].apply(lambda x: get_bin(x, score_right_list))
df_score.to_csv(path_ + '_modeling_score.csv', index=False)
print(10 * '*' + 'odds:', odds)
print(10 * '*' + 'finish logstic modeling')
print('spend times:', time.time() - start_time)
def read_big_file(file_in):
data = pd.read_csv(file_in, iterator=True)
loop = True
chunkSize = 100000
chunks = []
while loop:
try:
chunk = data.get_chunk(chunkSize)
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped.")
df_train = pd.concat(chunks, ignore_index=True)
return df_train
def output_score(file_in, model_vars, score_right_list=None):
# encoding = tool.file_encoding(file_in)
df = tool.read_file(file_in)
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
path_ = tool.prepare_path(project_name, 'd04_')
tag = param_dic['tag']
key = param_dic['key']
fin_model_vars = model_vars
fin_model_vars.extend([key, tag])
Xpath_ = tool.prepare_path(project_name, 'd02_')
f = open(Xpath_ + '_vars_woe_bin_dic.pkl', "rb")
dic_woe = pickle.load(f)
f = pd.read_excel(path_ + '_result.xlsx', sheet_name=u'评分卡刻度及公式')
odds = float(f['odds'][0])
print(10 * '*' + 'start to apply woe' + 10 * '*')
m_data_cross = apply_woe(df[fin_model_vars], dic_woe, str_vars, key, tag, path=path_ + '_cross')
print(10 * '*' + 'finish apply woe' + 10 * '*')
m_data_train = tool.read_file('./data/' + project_name + '_m_data_train_bin.pkl')
nd_vars_woe = [i + "_woe" for i in model_vars
if i + "_woe" in m_data_cross.columns]
for i in nd_vars_woe:
m_data_train[i] = m_data_train[i].astype(float)
m_data_cross[i] = m_data_cross[i].astype(float)
nd_vars_bin = [i[:-4] + '_bin' for i in nd_vars_woe]
# 加载模型
result = joblib.load(path_ + '_fin.model')
df_gp_uncut, df_gp_cut, df_gp_qcut, ks_df, p, df_rs_score = cal_ks_test(result, m_data_cross, tag,
base_score=base_score,
double_score=double_score, odds=odds)
writer = pd.ExcelWriter(path_ + '_cross_result.xlsx')
title_Style = writer.book.add_format(tool.title_Style)
cell_Style = writer.book.add_format(tool.cell_Style)
# 跨时间集汇总指标
ws_ks_df = writer.book.add_worksheet('跨时间集汇总指标')
df_rs_score = df_rs_score[[key, tag, 'score']]
df_rs_score['score_bin'] = df_rs_score['score'].apply(lambda x: get_bin(x, score_right_list))
df_score = pd.read_csv(path_ + '_modeling_score.csv')
model_ks, model_df = gb_add_woe(df_score, tag, 'artificial')
cross_ks, cross_df = gb_add_woe(df_rs_score, tag, 'artificial')
model_df = model_df[['bin', 'good', 'bad', 'bad_rate', 'bin_pct']]
cross_df = cross_df[['bin', 'good', 'bad', 'bad_rate', 'bin_pct']]
model_df.index = model_df['bin']
cross_df.index = cross_df['bin']
df_score_res = pd.concat([model_df, cross_df], axis=1, keys=['TRAIN', 'CROSS'], sort=False)
df_score_res['PSI'] = (df_score_res[('TRAIN', 'bin_pct')] - df_score_res[('CROSS', 'bin_pct')]) * np.log(
df_score_res[('TRAIN', 'bin_pct')] / df_score_res[('CROSS', 'bin_pct')])
psi = sum([ii for ii in df_score_res['PSI'] if not pd.isnull(ii)])
psi_df = pd.DataFrame({'describe': [psi]})
psi_df.index = ['PSI']
all_result = pd.concat([ks_df, psi_df])
all_result = all_result.reset_index()
all_result.columns = ['跨时间集', 'describe']
print(all_result)
df_score_res = df_score_res.reset_index(drop=True)
base_bin = list(set(model_df['bin']) | set(cross_df['bin']))
newbase = pd.DataFrame({'base_bin': base_bin})
newbase = newbase.sort_values('base_bin')
model_df = model_df.reset_index(drop=True)
model_df_new = pd.merge(newbase, model_df, left_on='base_bin', right_on='bin', how='left')
model_df_new.drop(columns=['bin'], inplace=True)
cross_df = cross_df.reset_index(drop=True)
cross_df_new = pd.merge(newbase, cross_df, left_on='base_bin', right_on='bin', how='left')
cross_df_new.drop(columns=['bin'], inplace=True)
row_num = all_result.shape[0]
summary_df = all_result.fillna('')
ws_ks_df.write_row(0, 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws_ks_df.write_row(1 + ii, 0, summary_df.loc[ii,], cell_Style)
ws_ks_df.set_column(0, summary_df.shape[1], 20)
# 各分数段分布
df_score_res.to_excel(writer, sheet_name='各分数段训练_跨时间集分布对比', startcol=0)
df_rs_score.to_excel(writer, sheet_name='跨时间集打分明细', index=False)
# 入模特征psi汇总指标及分箱明细对比
func_tt_vardescrible(m_data_train, m_data_cross, writer, nd_vars_bin, tag)
# 跨时间样本匹配不成功字段列表明细(如无匹配不成功则不输出文件)
root_path = path_.replace('d04_' + project_name, '')
error_file = [ii for ii in os.listdir(root_path) if ii.find('_var_error_value.csv') >= 0]
if error_file:
for ii in error_file:
df = tool.read_file(root_path + ii, header=-1)
df.columns = ['var_name', 'value', 'flag']
df.drop_duplicates(inplace=True)
df.to_csv(root_path + ii, index=False)
print(10 * '*' + '存在特征未匹配到分箱请查看文件%s' % root_path + ii + 10 * '*')
writer.save()
def output_score_psi(file_in, model_vars, score_right_list=None):
df = tool.read_file(file_in)
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
path_ = tool.prepare_path(project_name, 'd04_')
tag = param_dic['tag']
key = param_dic['key']
fin_model_vars = model_vars
fin_model_vars.extend([key, tag])
Xpath_ = tool.prepare_path(project_name, 'd02_')
f = open(Xpath_ + '_vars_woe_bin_dic.pkl', "rb")
dic_woe = pickle.load(f)
print(10 * '*' + 'start to apply woe' + 10 * '*')
m_data_cross = apply_woe(df[fin_model_vars], dic_woe, str_vars, key, tag, path=path_ + '_cross')
print(10 * '*' + 'finish apply woe' + 10 * '*')
m_data_train = tool.read_file('./data/' + project_name + '_m_data_train_bin.pkl')
nd_vars_woe = [i + "_woe" for i in model_vars
if i + "_woe" in m_data_cross.columns]
for i in nd_vars_woe:
m_data_train[i] = m_data_train[i].astype(float)
m_data_cross[i] = m_data_cross[i].astype(float)
nd_vars_bin = [i[:-4] + '_bin' for i in nd_vars_woe]
writer = pd.ExcelWriter(path_ + '_cross_result_vars_psi.xlsx')
func_tt_vardescrible(m_data_train, m_data_cross, writer, nd_vars_bin, tag)
root_path = path_.replace('d04_' + project_name, '')
error_file = [ii for ii in os.listdir(root_path) if ii.find('_var_error_value.csv') >= 0]
if error_file:
for ii in error_file:
df = tool.read_file(root_path + ii, header=-1)
df.columns = ['var_name', 'value', 'flag']
df.drop_duplicates(inplace=True)
df.to_csv(root_path + ii, index=False)
print(10 * '*' + '存在特征未匹配到分箱请查看文件%s' % root_path + ii + 10 * '*')
writer.save()
if __name__ == "__main__":
data_var_type = pd.read_excel('./data/data_source.xlsx')
str_vars = set(data_var_type[data_var_type['var_type'] == 'str']['var_name'].tolist())
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
base_score = param_dic['base_score']
double_score = param_dic['double_score']
ex_cols = param_dic['ex_cols']
nece_var = param_dic['nece_var']
step = param_dic['step']
is_all_necess = param_dic['is_all_necess']
bin_ex_corr = param_dic['bin_ex_corr']
model_ex_corr = param_dic['model_ex_corr']
model_vars_psi = param_dic['model_vars_psi']
path_ = tool.prepare_path(project_name, 'd04_')
# 设定分数右边界list,默认左开右闭
score_right_list = []
for i in range(0, 31):
score_right_list.append(10 * i + 400)
# 弹出输入窗
# try:
# model_step = int(input("model step:"))
# if model_step > 3 or model_step < 1:
# print ('input error ,please input int number in[1,2,3]')
# os._exit(0)
# except:
# print('input error ,please input int number in[1,2,3]')
# os._exit(0)
# # 首次训练模型
if step == 1:
print(10 * "*" + 'run model step %d' % step + 10 * "*")
model(model_ex_corr=model_ex_corr)
print(10 * "*" + 'finish model step %d' % step + 10 * "*")
# # 调试模型
if step == 2:
print(10 * "*" + 'run model step %d' % step + 10 * "*")
model_tune(tune_del_vars=ex_cols, tune_nec_vars=nece_var, is_all_necess=is_all_necess,
score_right_list=score_right_list)
print(10 * "*" + 'finish model step %d' % step + 10 * "*")
# # 跨时间样本打分
if step == 3:
print(10 * "*" + 'run model step %d' % step + 10 * "*")
# model_vars = pd.read_csv(path_ + '_fin_model_vars.csv')
# model_vars = model_vars['fin_vars'].tolist()
f = pd.read_excel(path_ + '_result.xlsx', sheet_name=u'最终入模特征', skiprows=1)
nan_index = list(f['特征简称']).index((np.nan))
model_vars_list = [ii for ii in list(f['特征简称'])[:nan_index] if ii != 'intercept']
file_in = './data/' + param_dic['cross_sample']
output_score(file_in, model_vars_list, score_right_list)
print(10 * "*" + 'finish model step %d' % step + 10 * "*")
# # 跨时间样本变量psi
if step == 4:
print(10 * "*" + 'run model step %d' % step + 10 * "*")
# model_vars_psi=[]
file_in = './data/' + param_dic['cross_sample']
output_score_psi(file_in, model_vars_psi)
print(10 * "*" + 'finish model step %d' % step + 10 * "*")
<file_sep># -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import tool
from numpy import array
def gb_add_woe(data):
df_gp = data.copy()
df_gp['pct_default'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
df_gp = df_gp.sort_values(by=['pct_default'], ascending=False)
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
df_gp['bad_pct'] = df_gp['bad'] / bad_sum
df_gp['good_pct'] = df_gp['good'] / good_sum
df_gp['odds'] = df_gp['good_pct'] - df_gp['bad_pct']
df_gp['Woe'] = np.log(df_gp['good_pct'] / df_gp['bad_pct'])
df_gp['IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
df_gp['bad_cnt'] = df_gp['bad'].cumsum()
df_gp['good_cnt'] = df_gp['good'].cumsum()
df_gp['b_c_p'] = df_gp['bad_cnt'] / bad_sum
df_gp['g_c_p'] = df_gp['good_cnt'] / good_sum
df_gp['KS'] = abs(df_gp['g_c_p'] - df_gp['b_c_p'])
ks_max = df_gp['KS'].max()
return ks_max, df_gp
def set_tag(x):
if x == 1:
y = 1
z = 0
else:
y = 0
z = 1
return y, z
def cut_method(data1, factor_name, flag_name, method, n):
data = data1.copy()
if method == 'qcut':
data[factor_name] = pd.qcut(data[factor_name], n, duplicates='drop')
elif method == 'cut':
data[factor_name] = pd.cut(data[factor_name], n)
elif method == 'uncut':
data[factor_name] = data[factor_name][:]
elif method == 'cumsum':
values = pd.DataFrame(data[factor_name].value_counts()).sort_index()
values['cum'] = values[factor_name].cumsum()
# sort_values=np.sort(data[factor_name].value_counts().index)
sum = data[factor_name].shape[0]
sd_bin = sum / n
botton = float(list(values.index)[0]) - 0.001
values_c = values.copy()
bin = []
for i in range(n):
values_i = values_c[values_c['cum'] <= sd_bin]
if values_i.shape[0] == 0:
top = list(values_c.index)[0]
else:
top = list(values_i.index)[-1]
bin.append([botton, top])
botton = top
values_c = values_c[values_c.index > top]
values_c['cum'] = values_c[factor_name].cumsum()
if values_c.shape[0] == 0:
break
# bin=[]
# for i in sort_values:
# data_i=data[(data[factor_name]>botton)&(data[factor_name]<=i)]
# if data_i.shape[0]>sd_bin:
# bin.append([botton,i])
# botton=i
bin.append([botton, list(values.index)[-1]])
data[factor_name] = data[factor_name].map(lambda x: find_bin(x, bin))
return data
def find_bin(x, list_bin):
for i in list_bin:
if x > i[0] and x <= i[1]:
y = str(i)
try:
return y
except:
print(x, list_bin)
def loop(df, factor_name, flag_name, method):
'''
用于寻找保证单调性下的最大分Bin组数
:param df:
:param factor_name:
:param ex_value:
:return:
'''
find_n = []
data_for_cut = df.copy()
for n in range(2, 10, 1):
print('loop to ', n)
# try:
data_1 = cut_method(data_for_cut, factor_name, flag_name, method, n)
data_gp = data_1.groupby(factor_name).sum()
data_gp['sort'] = data_gp.index.map(lambda x: float(x.split(',')[0][1:]))
df_jugde = data_gp.sort_values('sort').drop('sort', axis=1)
# pct_list=gb_add_woe(df_jugde)[1]['pct_default'].tolist()
pct_list = list(df_jugde['bad'] / (df_jugde['bad'] + df_jugde['good']))
if pd.Series(pct_list).is_monotonic_decreasing or pd.Series(pct_list).is_monotonic_increasing:
find_n.append(n)
else:
break
# except Exception,e:
# print Exception,e
# print 'cant cut more'
# break
# print find_n
max_n = max(find_n)
return max_n
def format_dtype(x,var_type):
try:
if pd.isnull(x) or x.find('NAN')>=0:
return (x)
elif var_type=='str':
return str(x)
else:
return float(x)
except:
print('error',x)
return 'error'
def cut_cumsum_bin(data, factor_name, flag_name, not_in_list, method, mono=True, bin_num=20,var_type=''):
data = data[[factor_name, flag_name]].fillna('NAN')
data['bad'] = data[flag_name].map(lambda x: set_tag(x)[0])
data['good'] = data[flag_name].map(lambda x: set_tag(x)[1])
df_ex1 = data[data[factor_name].map(lambda x: str(x) in not_in_list)] # 分割需要单独切出的bin值(-1,nan),单独值的bin使用[a,a]来表示
df_ex = df_ex1.copy()
df_ex[factor_name] = df_ex[factor_name].map(lambda x: '(' + str(x) + ',' + str(x) + ')')
df_rm1 = data[data[factor_name].map(lambda x: str(x) not in not_in_list)]
##
if mono:
n = loop(df_rm1, factor_name, flag_name, method)
else:
n = min(bin_num, len(set(data[factor_name])))
# print 'cut',n
df_rm = df_rm1.copy()
df_rm[factor_name] = cut_method(df_rm, factor_name, flag_name, method, n)
# print df_rm
df = pd.concat([df_ex, df_rm], axis=0)
df_ = df.groupby(factor_name).sum()[['bad', 'good']]
df_gp = gb_add_woe(df_)[1]
df_gp[factor_name] = df_gp.index
# df_gp['sort'] = df_gp[factor_name].map(lambda x: float(str(x).split(',')[0][1:]))
df_gp = df_gp.sort_values('pct_default')
df_new = df_gp.copy()
df_new['Total_Num'] = df_new['bad'] + df_new['good']
df_new['Bad_Num'] = df_new['bad']
df_new['Good_Num'] = df_new['good']
df_new['Total_Pcnt'] = df_new['Total_Num'] / df_new['Total_Num'].sum()
df_new['Bad_Rate'] = df_new['Bad_Num'] / df_new['Total_Num']
df_new['Good_Rate'] = df_new['Good_Num'] / df_new['Total_Num']
df_new['Good_Pcnt'] = df_new['Good_Num'] / df_new['Good_Num'].sum()
df_new['Bad_Pcnt'] = df_new['Bad_Num'] / df_new['Bad_Num'].sum()
df_new['Bad_Cum'] = df_new['b_c_p']
df_new['Good_Cum'] = df_new['g_c_p']
df_new['Gini'] = 1 - pow(array(list(df_new['Good_Rate'])), 2) - pow(array(list(df_new['Bad_Rate'])), 2)
df_new = df_new[
[factor_name, 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate', 'Good_Rate', 'Good_Pcnt',
'Bad_Pcnt', 'Bad_Cum', 'Good_Cum', 'Woe', 'IV', 'Gini', 'KS']]
if method == 'uncut':
df_new.columns = [factor_name + '_tmp', 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate',
'Good_Rate',
'Good_Pcnt',
'Bad_Pcnt', 'Bad_Cum', 'Good_Cum', 'Woe', 'IV', 'Gini', 'KS']
df_new[factor_name] = df_new[factor_name + '_tmp'].apply(
lambda x: str(x) if str(x).find('NAN') >= 0 else '[' + str(x) + ',' + str(x) + ']')
df_new_p1=df_new[df_new[factor_name + '_tmp'].apply(lambda x: str(x).find('NAN')>=0)]
df_new_p2=df_new[df_new[factor_name + '_tmp'].apply(lambda x: str(x).find('NAN')<0)]
df_new_p2 = df_new_p2.sort_values(factor_name + '_tmp', ascending=True)
df_new=pd.concat([df_new_p1,df_new_p2])
df_new = df_new[
[factor_name, 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate', 'Good_Rate', 'Good_Pcnt',
'Bad_Pcnt', 'Bad_Cum', 'Good_Cum', 'Woe', 'IV', 'Gini', 'KS']]
df_new = df_new.reset_index(drop=True)
else:
df_new[factor_name] = df_new[factor_name].apply(
lambda x: '(' + str(x) + ',' + str(x) + ')' if str(x).find('NAN') >= 0 else x)
df_new = df_new.reset_index(drop=True)
df_new = df_new.sort_values(factor_name, ascending=True)
# total_num=sum(df_gp['good'])+sum(df_gp['bad'])
# df_gp.columns=['Bad_Num','Good_Num','Bad_Rate','Good_Rate','odds','Woe','IV','Bad_cnt','Good_cnt','bcp','gcp','KS','rej_pct','sort','var_name']
# df_gp['Total_Num']=df_gp['Good_Num']+df_gp['Bad_Num']
# df_gp['Total_Pcnt']=df_gp['Total_Num']/total_num
# df_gp[factor_name]=df_gp.index.tolist()
return df_new
##
# try:
# # print 'loop'
# if mono:
# n = loop(df_rm1, factor_name, flag_name, method)
# else:
# n = max(20, len(set(data[factor_name])))
# # print 'cut',n
# df_rm = df_rm1.copy()
# df_rm[factor_name] = cut_method(df_rm, factor_name, flag_name, method, n)
#
# # print df_rm
# df = pd.concat([df_ex, df_rm], axis=0)
# df_ = df.groupby(factor_name).sum()[['bad', 'good']]
# df_gp = gb_add_woe(df_)[1]
# df_gp[factor_name] = df_gp.index
# # df_gp['sort'] = df_gp[factor_name].map(lambda x: float(str(x).split(',')[0][1:]))
# df_gp = df_gp.sort_values('pct_default')
# df_new = df_gp.copy()
# df_new['Total_Num'] = df_new['bad'] + df_new['good']
# df_new['Bad_Num'] = df_new['bad']
# df_new['Good_Num'] = df_new['good']
# df_new['Total_Pcnt'] = df_new['Total_Num'] / df_new['Total_Num'].sum()
# df_new['Bad_Rate'] = df_new['Bad_Num'] / df_new['Total_Num']
# df_new['Good_Rate'] = df_new['Good_Num'] / df_new['Total_Num']
# df_new['Good_Pcnt'] = df_new['Good_Num'] / df_new['Good_Num'].sum()
# df_new['Bad_Pcnt'] = df_new['Bad_Num'] / df_new['Bad_Num'].sum()
# df_new['Bad_Cum'] = df_new['b_c_p']
# df_new['Good_Cum'] = df_new['g_c_p']
# df_new['Gini'] = 1 - pow(array(list(df_new['Good_Rate'])), 2) - pow(array(list(df_new['Bad_Rate'])), 2)
# df_new = df_new[[factor_name,
# 'Total_Num',
# 'Bad_Num',
# 'Good_Num',
# 'Total_Pcnt',
# 'Bad_Rate',
# 'Good_Rate',
# 'Good_Pcnt',
# 'Bad_Pcnt',
# 'Bad_Cum',
# 'Good_Cum',
# 'Woe',
# 'IV',
# 'Gini',
# 'KS']]
# df_new[factor_name]=df_new[factor_name].apply(lambda x: x if str(x).find('NAN')>=0 else '(' + str(x) + ',' + str(x) +')')
# # total_num=sum(df_gp['good'])+sum(df_gp['bad'])
# # df_gp.columns=['Bad_Num','Good_Num','Bad_Rate','Good_Rate','odds','Woe','IV','Bad_cnt','Good_cnt','bcp','gcp','KS','rej_pct','sort','var_name']
# # df_gp['Total_Num']=df_gp['Good_Num']+df_gp['Bad_Num']
# # df_gp['Total_Pcnt']=df_gp['Total_Num']/total_num
# # df_gp[factor_name]=df_gp.index.tolist()
# df_new = df_new.sort_values('Bad_Rate',ascending=False)
# df_new=df_new.reset_index()
# return df_new
# except Exception as e:
# print('cannot cut more')
# print(Exception, e)
# return []
# dic_a=cut_bin_best_ks(rule,['appid','c.create_date','c.end_date','tag3','c.is_overdue','c.overdue_day'],'rule_check','tag3',mono=False)
def multicut_var(data_var):
pass
# import time
# a=cut_cumsum_bin(data=m_data_train,flag_name='tag7',
# factor_name='call_in_cell_days_sum_j1m',not_in_list=['NAN','-1.0'],method='cumsum',mono=False)
#
# loop(df,factor_name,flag_name,method)
#
#
# df,factor_name,flag_name,method=test1[['callOut2101TimeMinJ5m','tag']],'callOut2101TimeMinJ5m','tag','cumsum'
# Best_KS_Bin(data=data[[i,'black_flag']],flag_name='black_flag',
# factor_name=i,not_in_list=['NaN','-1.0',''])
def chi_square_bin(data, flag_name: str, factor_name: str, not_in_list=['NaN', 'NAN'], mono=False, bin_num=5,
var_type='number'):
from binning.supervised import ChiSquareBinning
import time
# X = pd.DataFrame({'a': [random.randint(1, 20) for _ in range(1000)],
# 'b': [random.randint(1, 20) for _ in range(1000)],
# 'c': [random.randint(1, 20) for _ in range(1000)]})
# y = [int(random.random() > 0.5) for _ in range(1000)]
X = data[[factor_name]]
y = data[flag_name]
if var_type == 'str':
categorical_cols = [factor_name]
else:
categorical_cols = []
CB = ChiSquareBinning(max_bin=10, categorical_cols=categorical_cols, force_mix_label=False, force_monotonic=mono,
prebin=100, encode=True, strict=False)
CB.fit(X, y)
var_bin_list = (CB.bins)[factor_name]
print(var_bin_list)
transform_bin = CB.transform(X)
transform_bin.columns = [ii + '_bin_num' for ii in transform_bin.columns]
fin = pd.concat([X, transform_bin, y], axis=1)
var_dict = dict()
if var_type == 'str':
dist_num = fin[factor_name + '_bin_num'].unique()
for ii in dist_num:
var_str_l = list(set(fin[fin[factor_name + '_bin_num'] == ii][factor_name].tolist()))
if ii == -1:
var_str_l = '(NAN,NAN)'
var_dict[ii] = var_str_l
else:
var_dict[ii] = '(%s)' % ','.join(var_str_l)
else:
dist_num = fin[factor_name + '_bin_num'].unique()
if -1 in dist_num:
var_str_l = '(NAN,NAN)'
var_dict[-1] = var_str_l
right_max = var_bin_list[1:]
bin_list = tool.get_bin_cate(right_max)
for ii in range(len(bin_list)):
var_dict[ii + 1] = bin_list[ii]
fin[factor_name + '_bin'] = fin[factor_name + '_bin_num'].apply(lambda x: var_dict[x])
new_fin = fin[[factor_name + '_bin', flag_name]]
new_fin.columns = [factor_name, flag_name]
new_fin['bad'] = new_fin[flag_name].map(lambda x: set_tag(x)[0])
new_fin['good'] = new_fin[flag_name].map(lambda x: set_tag(x)[1])
df_ = new_fin.groupby(factor_name).sum()[['bad', 'good']]
df_gp = gb_add_woe(df_)[1]
df_gp[factor_name] = df_gp.index
# df_gp['sort'] = df_gp[factor_name].map(lambda x: float(str(x).split(',')[0][1:]))
# df_gp = df_gp.sort_values('pct_default')
df_new = df_gp.copy()
df_new['Total_Num'] = df_new['bad'] + df_new['good']
df_new['Bad_Num'] = df_new['bad']
df_new['Good_Num'] = df_new['good']
df_new['Total_Pcnt'] = df_new['Total_Num'] / df_new['Total_Num'].sum()
df_new['Bad_Rate'] = df_new['Bad_Num'] / df_new['Total_Num']
df_new['Good_Rate'] = df_new['Good_Num'] / df_new['Total_Num']
df_new['Good_Pcnt'] = df_new['Good_Num'] / df_new['Good_Num'].sum()
df_new['Bad_Pcnt'] = df_new['Bad_Num'] / df_new['Bad_Num'].sum()
df_new['Bad_Cum'] = df_new['b_c_p']
df_new['Good_Cum'] = df_new['g_c_p']
df_new['Gini'] = 1 - pow(array(list(df_new['Good_Rate'])), 2) - pow(array(list(df_new['Bad_Rate'])), 2)
df_new = df_new[
[factor_name, 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate', 'Good_Rate', 'Good_Pcnt',
'Bad_Pcnt', 'Bad_Cum', 'Good_Cum', 'Woe', 'IV', 'Gini', 'KS']]
df_new = df_new.reset_index(drop=True)
return df_new
<file_sep>import pandas as pd
import tool
def create_rule(data,rule_data,rand_num=[]):
var_list=list(rule_data['var_name'].unqiue())
if len(vars)==0:
print('error')
else:
for num in rand_num:
new_list=tool.combine(rule_data,num)
def ai_rule_test():
df=pd.read_csv('./data.csv')
df['is_touch']=((df['var1']>10)&(df['var2']>10)|(df['var3']>10))
sample_num=df.shape[0]
var_name='is_touch'
y_flag='y2_new'
df_i=df[[var_name,y_flag]].fillna('Null')
new=df_i[y_flag].groupby([df_i[var_name],df_i[y_flag]]).count().unstack().reset_index().fillna(0)
new.columns=['var_value','good','bad']
new['bin_num']=new['good']+new['bad']
new['bad_rate']=new['bad']/new['total']
new['bin_rate']=new['bin_num']/sample_num
print(new)<file_sep># -*- coding:utf-8 -*-
import logging
import logging.config
import pandas as pd
import d00_param
import imp
import tool
import numpy as np
import sys
from binning.drawwoe import draw_woe_fromdic
from binning.cumsum_cut import cut_cumsum_bin, chi_square_bin
from binning.best_ks_3 import Best_KS_Bin, apply_woe, filter_by_corr, func_tt_vardescrible
imp.reload(d00_param)
imp.reload(tool)
def _log_(log_file_name=None, stdout_on=False):
log_file_name = log_file_name if log_file_name is not None else (__name__ + '.log')
logger_ = logging.getLogger("riskengine")
fmt = '[%(asctime)s.%(msecs)d][%(name)s][%(levelname)s]%(msg)s'
date_fmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(fmt=fmt, datefmt=date_fmt)
if stdout_on:
stout_handler = logging.StreamHandler(sys.stdout)
stout_handler.setFormatter(formatter)
logger_.addHandler(stout_handler)
file_handler = logging.FileHandler(log_file_name, encoding='utf-8')
file_handler.setFormatter(formatter)
logger_.addHandler(file_handler)
logger_.setLevel(logging.DEBUG)
return logger_
def ex_inf_sum(list_x, method):
list_y = [i for i in list_x if i not in [np.inf, -np.inf, 'inf', '-inf', np.nan, 'nan', 'null', 'NAN']]
if method == 'SUM':
return sum(list_y)
if method == 'MAX':
return max(list_y)
def cut_bin_choose(df_train, df_test, exclude_var, path_, tag, ex_1=False,
mono=True, manual=False, test_size=0.0, bin_ex_corr=False):
'''
:param df_train: 训练数据集[id,vars,tag]
:param df_test: 测试数据集
:param exclude_var: 剔除变量
:param path_: 文件路径
:param tag: Y标签
:param ex_1: 是否对变量-1值剔除分箱
:param enble_bin_way: 分箱方式:best_ks,uncut
:param mono: 是否单调
:param manual: 是否人工分箱
:param bin_num: 分箱最大数
:return:
'''
logger = _log_(log_file_name=path_ + "_execute.log", stdout_on=False)
data = df_train.copy()
all_vars = data.columns.tolist()
data_var_type = pd.read_excel('./data/data_source.xlsx')
Xpath_ = tool.prepare_path(project_name, 'd01_')
df_describe = pd.read_excel(Xpath_ + '_x_describe_info.xlsx', sheet_name=u'特征探查分布情况')
df_describe = df_describe[[u'特征中文名', u'覆盖率']]
df_describe = df_describe.set_index(u'特征中文名').to_dict('index')
data_dic = data_var_type.set_index('var_name').to_dict('index')
str_vars = data_var_type[data_var_type['var_type'] == 'str']['var_name'].tolist()
vars = list(set(all_vars) - set(exclude_var))
dic_woe = {}
dic_df = {}
cant_col = []
import pickle
writer = pd.ExcelWriter(path_ + '_info.xlsx')
ws1 = writer.book.add_worksheet('特征IV汇总')
ws2 = writer.book.add_worksheet('特征分箱明细')
title_Style = writer.book.add_format(tool.title_Style)
cell_Style = writer.book.add_format(tool.cell_Style)
num = 0
summary = []
# vars = ['devicetype','certi_city_level']
var_dict = dict()
cnt = 1
print(10 * '*' + 'start auto woe bin.' + 10 * '*')
for var_names in vars:
logger.info('VAR_BIN PREPARE :%s' % var_names)
print('VAR_BIN PREPARE :' + var_names)
#
if ex_1:
data_cut = data[data[var_names] != -1] # todo
else:
data_cut = data.copy()
var_type = data_dic[var_names]['var_type']
cut_bin_way = data_dic[var_names]['cut_bin_way']
cut_bin_num = data_dic[var_names]['cut_bin_num']
if cut_bin_way == 'best_ks':
# flag_name Y标签 ; factor_name变量名 ; rate 分组占比不得小于的比例
df_1 = Best_KS_Bin(data=data_cut[[var_names, tag]], flag_name=tag, factor_name=var_names,
not_in_list=['NaN', 'NAN'], rate=0.02, bin_num=cut_bin_num, var_type=var_type, mono=mono)
elif cut_bin_way == 'uncut':
df_1 = cut_cumsum_bin(data=data_cut[[var_names, tag]], flag_name=tag,
factor_name=var_names, not_in_list=['NaN', 'NAN'],
method='uncut', var_type=var_type,
mono=False)
print(df_1)
elif var_type == 'number' and cut_bin_way in ['qcut', 'equidist_cut']:
if cut_bin_way == 'qcut':
df_1 = cut_cumsum_bin(data=data_cut[[var_names, tag]], flag_name=tag,
factor_name=var_names, not_in_list=['NaN', 'NAN'],
method='qcut', bin_num=cut_bin_num,
mono=False)
elif cut_bin_way == 'equidist_cut':
df_1 = cut_cumsum_bin(data=data_cut[[var_names, tag]], flag_name=tag,
factor_name=var_names, not_in_list=['NaN', 'NAN'],
method='cut',
mono=False, bin_num=cut_bin_num)
else:
print("cut_error")
elif cut_bin_way == 'chi_square':
df_1 = chi_square_bin(data=data_cut[[var_names, tag]], flag_name=tag,
factor_name=var_names, not_in_list=['NaN', 'NAN'],
mono=mono, bin_num=cut_bin_num, var_type=var_type)
if len(df_1) == 0:
print("NULL VAR")
else:
dic_df[var_names] = df_1
df_1['var_name'] = [str(var_names) for _ in range(len(df_1))]
woe_value = df_1['Woe']
bin_name = df_1[var_names]
dic_woe[var_names] = dict(zip(list(bin_name), list(woe_value)))
summary.append([var_names, df_1.shape[0], ex_inf_sum(df_1['IV'], 'SUM'),
ex_inf_sum(df_1['KS'], 'MAX')])
# df_1.to_excel(writer, 'detail', startrow=num)
df_1 = df_1[[var_names, 'Total_Num', 'Bad_Num', 'Good_Num', 'Total_Pcnt', 'Bad_Rate', 'Woe',
'IV', 'Gini', 'KS', 'var_name']]
df_1.columns = [var_names, '样本总数', '坏样本数', '好样本数', '分箱占比', '坏样本占比', 'Woe',
'IV', 'Gini', 'KS', 'var_name']
rows = df_1.shape[0]
df_1 = df_1.fillna('')
ws2.write_row(num, 0, df_1.columns, title_Style)
for ii in range(rows):
ws2.write_row(1 + ii + num, 0, df_1.loc[ii,], cell_Style)
if cnt == 1:
ws2.set_column(0, 0, 20)
ws2.set_column(1, df_1.shape[1], 10)
cnt += 1
var_dict[var_names] = num
num += len(df_1) + 3
f = open(path_ + '_vars_woe_bin_dic.pkl', 'wb+')
pickle.dump(dic_woe, f)
f.close()
summary_df = pd.DataFrame(summary,
columns=['var', 'group_num', 'iv', 'ks'])
summary_df = summary_df.sort_values('iv', ascending=False).reset_index(drop=True)
summary_df['chn_meaning'] = summary_df['var'].apply(lambda x: data_dic[x]['chn_meaning'])
summary_df['覆盖率'] = summary_df['var'].apply(lambda x: df_describe[x][u'覆盖率'])
summary_df.columns = [u'特征简称', u'特征分箱数', 'IV', 'KS', u'特征中文名', u'覆盖率']
fin_vars = list(summary_df[u'特征简称'])
fin_vars.extend([key, tag])
print(10 * '*' + 'finish auto woe bin.' + 10 * '*')
if bin_ex_corr:
print(10 * '*' + 'start to apply woe.' + 10 * '*')
print(10 * '*' + 'wait....' + 10 * '*')
# ##test
# vars=[key, tag,'usermobileonlinedd','sex','credit_channel_name','register_channel_name']
# ##
m_data_train = apply_woe(df_train[fin_vars], dic_woe, str_vars, key, tag, path=path_)
m_data_test = apply_woe(df_test[fin_vars], dic_woe, str_vars, key, tag, path=path_)
print(10 * '*' + 'finish apply woe.' + 10 * '*')
print(10 * '*' + 'start to exclude corr.' + 10 * '*')
corr_limit = param_dic['corr_limit']
nd_vars_woe = filter_by_corr(m_data_train, fin_vars, nec_vars=[], corr_limit=corr_limit)
for i in nd_vars_woe:
m_data_train[i] = m_data_train[i].astype(float)
m_data_test[i] = m_data_test[i].astype(float)
m_data_train_new = m_data_train[[ii for ii in m_data_train if ii[-4:] != '_bin']]
m_data_test_new = m_data_test[[ii for ii in m_data_train if ii[-4:] != '_bin']]
m_data_train.to_pickle('./data/' + project_name + '_m_data_train_bin.pkl')
m_data_train_new.to_pickle('./data/' + project_name + '_m_data_train.pkl')
m_data_test_new.to_pickle('./data/' + project_name + '_m_data_test.pkl')
# nd_vars_bin = [i[:-4] + '_bin' for i in nd_vars_woe]
# print(10 * '*' + 'start ttdescribe.' + 10 * '*')
# if test_size > 0:
# func_tt_vardescrible(m_data_train, m_data_test, nd_vars_bin, path_, tag, 'model')
# print(10 * '*' + 'finish ttdescribe.' + 10 * '*')
nd_vars = [i[:-4] for i in nd_vars_woe]
summary_df[u'是否因超过共线性阀值剔除'] = summary_df['特征简称'].apply(lambda x: 0 if x in set(nd_vars) else 1)
print(10 * '*' + 'finish exclude corr.' + 10 * '*')
# summary_df.to_excel(writer, 'summary', startrow=0)
row_num = summary_df.shape[0]
summary_df = summary_df.fillna('')
ws1.write_row(0, 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws1.write_row(1 + ii, 0, summary_df.loc[ii,], cell_Style)
var_name = fin_vars[ii]
start_num = var_dict[var_name] + 1
link = "internal:'特征分箱明细'!A%s" % (str(start_num)) # 写超链接
ws1.write_url(ii + 1, 0, link, string=var_name)
ws1.set_column(0, 0, 25)
ws1.set_column(1, summary_df.shape[1], 15)
# df_train.describe().T.to_excel(writer, 'describe', startrow=0)
writer.save()
logger.info('VAR_BIN PREPARED , %s VARS CANNOT BE CUTTED' % str(len(cant_col)))
logger.info('VAR_BIN DICT HAS BEEN PREPARED : %s' % path_ + '/' + project_name + '_vars_woe_bin_dic.pkl')
# draw_woe_fromdic(dic_df, path_)
# print 'woe字典已保存'
# return dic_woe, summary_df
def cut_bin_choose_uncut(df_train, df_test, exclude_var, path_, tag, ex_1=False,
mono=True, manual=False, test_size=0.0, bin_ex_corr=False):
'''
:param df_train: 训练数据集[id,vars,tag]
:param df_test: 测试数据集
:param exclude_var: 剔除变量
:param path_: 文件路径
:param tag: Y标签
:param ex_1: 是否对变量-1值剔除分箱
:param enble_bin_way: 分箱方式:best_ks,uncut
:param mono: 是否单调
:param manual: 是否人工分箱
:param bin_num: 分箱最大数
:return:
'''
logger = _log_(log_file_name=path_ + "_execute.log", stdout_on=False)
data = df_train.copy()
all_vars = data.columns.tolist()
Xpath_ = tool.prepare_path(project_name, 'd01_')
df_describe = pd.read_excel(Xpath_ + '_x_describe_info.xlsx', sheet_name=u'特征探查分布情况')
df_describe = df_describe[[u'特征中文名', u'覆盖率']]
df_describe = df_describe.set_index(u'特征中文名').to_dict('index')
data_var_type = pd.read_excel('./data/data_source.xlsx')
data_dic = data_var_type.set_index('var_name').to_dict('index')
str_vars = data_var_type[data_var_type['var_type'] == 'str']['var_name'].tolist()
vars = list(set(all_vars) - set(exclude_var))
dic_woe = {}
dic_df = {}
import xlsxwriter
writer = xlsxwriter.Workbook(path_ + '_info_uncut.xlsx', {'nan_inf_to_errors': True})
ws1 = writer.add_worksheet('特征IV汇总')
ws2 = writer.add_worksheet('特征分箱明细')
title_Style = writer.add_format(tool.title_Style)
cell_Style = writer.add_format(tool.cell_Style)
num = 0
summary = []
# vars = ['m3还款提醒事件']
var_dict = dict()
print(10 * '*' + 'start uncut woe bin.' + 10 * '*')
for var_names in vars:
logger.info('VAR_BIN PREPARE :%s' % var_names)
print('VAR_BIN PREPARE :' + var_names)
#
if ex_1:
data_cut = data[data[var_names] != -1] # todo
else:
data_cut = data.copy()
var_type = data_dic[var_names]['var_type']
df_1 = cut_cumsum_bin(data=data_cut[[var_names, tag]], flag_name=tag,
factor_name=var_names, not_in_list=['NaN', 'NAN'],
method='uncut', var_type=var_type,
mono=False)
if len(df_1) == 0:
print("NULL VAR")
else:
dic_df[var_names] = df_1
df_1['var_name'] = [str(var_names) for _ in range(len(df_1))]
woe_value = df_1['Woe']
bin_name = df_1[var_names]
dic_woe[var_names] = dict(zip(list(bin_name), list(woe_value)))
summary.append([var_names, df_1.shape[0], ex_inf_sum(df_1['IV'], 'SUM'),
ex_inf_sum(df_1['KS'], 'MAX')])
# df_1.to_excel(writer, 'detail', startrow=num)
rows = df_1.shape[0]
df_1 = df_1.fillna('')
ws2.write_row(num, 0, df_1.columns)
for ii in range(rows):
ws2.write_row(1 + ii + num, 0, df_1.loc[ii,])
var_dict[var_names] = num
num += len(df_1) + 3
summary_df = pd.DataFrame(summary,
columns=['var', 'group_num', 'iv', 'ks'])
summary_df = summary_df.sort_values('iv', ascending=False).reset_index(drop=True)
summary_df['chn_meaning'] = summary_df['var'].apply(lambda x: data_dic[x]['chn_meaning'])
summary_df['覆盖率'] = summary_df['var'].apply(lambda x: df_describe[x][u'覆盖率'])
summary_df.columns = [u'特征简称', u'特征分箱数', 'IV', 'KS', u'特征中文名', u'覆盖率']
fin_vars = list(summary_df[u'特征简称'])
row_num = summary_df.shape[0]
summary_df = summary_df.fillna('')
ws1.write_row(0, 0, summary_df.columns, title_Style)
for ii in range(row_num):
ws1.write_row(1 + ii, 0, summary_df.loc[ii,], cell_Style)
var_name = fin_vars[ii]
start_num = var_dict[var_name] + 1
link = "internal:'特征分箱明细'!A%s" % (str(start_num)) # 写超链接
ws1.write_url(ii + 1, 0, link, string=var_name)
ws1.set_column(0, 0, 25)
ws1.set_column(1, summary_df.shape[1], 15)
writer.close()
print(10 * '*' + 'finish uncut woe bin.' + 10 * '*')
if __name__ == "__main__":
with tool.Timer() as t:
param_dic = d00_param.param_dic
project_name = param_dic['project_name']
path_ = tool.prepare_path(project_name, 'd02_')
ex_cols = param_dic['ex_cols']
tag = param_dic['tag']
key = param_dic['key']
test_size = param_dic['test_size']
bin_ex_corr = param_dic['bin_ex_corr']
mono = param_dic['mono']
auto_bin_num = param_dic['auto_bin_num']
nece_var = param_dic['nece_var']
output_auto_cut_bin = param_dic['output_auto_cut_bin']
output_uncut_bin = param_dic['output_uncut_bin']
df_train = tool.read_file('./data/' + project_name + '_df_train.pkl')
df_test = tool.read_file('./data/' + project_name + '_df_test.pkl')
if output_auto_cut_bin:
cut_bin_choose(df_train, df_test, ex_cols, path_, tag, mono=mono, test_size=test_size,
bin_ex_corr=bin_ex_corr)
if output_uncut_bin:
cut_bin_choose_uncut(df_train, df_test, ex_cols, path_, tag, mono=mono, test_size=test_size,
bin_ex_corr=bin_ex_corr)
print(t.secs)
<file_sep># -*- coding:utf-8 -*-
import pandas as pd
import statsmodels.api as sm
# import pylab as pl
import numpy as np
import math
# import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
# from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score
from modeling.cal_ks_auc_score import func_good,func_bad,cal_ks
from sklearn.utils import shuffle
def func_sort_col(col, df_, code):
'''
该函数用于将train_cols按wald_chi2排序:
:wald_chi2= (coef/se(coef))^2
:se(coef)=sd(coef)/n^2
:param col:trian_cols[list]
:param df_: m_data[pd.dataframe]
:param code: tag_name
:return: sorted_cols[list]
'''
cols = col[:]
dic_wald = {}
# for i in cols:
# dic_wald[i]=cal_wald_chi2(i,df_,code)
#
# wald_df=pd.DataFrame(dic_wald,index=['wald']).T
# sorted_cols=list(wald_df.sort_values('wald',ascending=False).index)
if 'intercept' not in cols:
cols.append('intercept')
df_['intercept'] = 1
cols = list(set(cols) & set(df_.columns))
logit_1 = sm.Logit(df_[code], df_[cols])
result_1 = logit_1.fit()
wald_chi2 = np.square((result_1.params) / np.square(result_1.bse))
a = pd.DataFrame(wald_chi2, columns=['value'])
b = a.sort_values('value', ascending=False)
sorted_cols = b.index.tolist()
sorted_cols.remove('intercept')
return a, sorted_cols
#
# def cal_wald_chi2(var,df_,code):
# try:
# df_['intercept']=1
# logit_i=sm.Logit(df_[code],df_[var])
# result_1=logit_i.fit()
# wald_chi2 = np.square((result_1.params) / np.square(result_1.bse))
# except Exception,E:
# print Exception,E
# wald_chi2=0
# return wald_chi2
# sorted_cols=func_sort_col(vars_,y_train,'tag7')
# def cal_ks_gp(df_rs,bin,tag):
# df_rs.ix[:,'good']=df_rs[tag].map(lambda x:func_good(x))
# df_rs.ix[:,'bad']=df_rs[tag].map(lambda x:func_bad(x))
# df_gp=df_rs.groupby([bin])['good','bad'].sum()
# bad_sum=df_gp['bad'].sum()
# good_sum=df_gp['good'].sum()
# bad_cnt=df_gp['bad'].cumsum()
# good_cnt=df_gp['good'].cumsum()
# df_gp.ix[:,'bad_cnt']=bad_cnt
# df_gp.ix[:,'good_cnt']=good_cnt
# df_gp['bad_pct']=df_gp['bad']/np.array([bad_sum for _ in range(len(df_gp))])
# df_gp['good_pct']=df_gp['good']/np.array([good_sum for _ in range(len(df_gp))])
# df_gp['Woe']=np.log(df_gp['good_pct']/df_gp['bad_pct'])
# df_gp['IV'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['Woe']
# df_gp.ix[:,'b_c_p']=df_gp['bad_cnt']/np.array([bad_sum for _ in range(len(df_gp))])
# df_gp.ix[:,'g_c_p']=df_gp['good_cnt']/np.array([good_sum for _ in range(len(df_gp))])
# df_gp.ix[:,'ks']=df_gp['g_c_p']-df_gp['b_c_p']
# ks_max=max(df_gp['ks'].map(lambda x :abs(x)))
# iv=sum(df_gp['IV'].tolist())
# return ks_max,iv
def func_sort_min_innerks(train_cols, data_path, tag):
t_data = pd.read_csv('T_Data_' + data_path + '.csv')
info = pd.read_excel('Info_' + data_path + '.xlsx')
test_ks = pd.DataFrame()
varname_list = []
varks_list = []
for i in train_cols:
data_i = t_data[[i[4:], tag, 'id']]
ks_i = gb_add_woe(data_i, i[4:])
varname_list.append(i[4:])
varks_list.append(ks_i)
test_ks['var'] = varname_list
test_ks['test_ks'] = varks_list
ks_df = pd.merge(test_ks, info, how='left', on='var')
ks_df['ks_dif'] = abs(ks_df['ks'] - ks_df['test_ks'])
ks_sort = ks_df.sort_values('ks_dif', ascending=True)
a = ks_sort['var'].tolist()
b = ['WOE_' + i for i in a]
print(ks_sort[['ks', 'test_ks', 'ks_dif']])
return b
# sorted_cols=func_sort_min_innerks(train_cols_cor,'yk_new_allvars','tag_x')
# cols=['WOE_'+i for i in sorted_cols]
def func_check_(x):
list_1 = list(x)
check = []
for i in list_1:
if i < 0:
check.append(1)
else:
check.append(0)
if sum(check) == len(list_1):
return True
else:
return False
# ##l2建模步骤
# def func_stepwise_1(cols, df_, code, report=None):
# '''
# :param cols: train_cols[list]
# :param df_: m_data[pd.df]
# :param code: tag_name
# :param sort: 是否需要进行排序:TRUE/FALSE
# :return: 入参变量
# '''
# vars_dic = {}
# import statsmodels.api as sm
# train_cols = ['intercept']
# df_['intercept'] = 1
# error_var = []
# sorted_cols = cols[:]
# num = 0
# if report:
# lr =LogisticRegression(penalty= 'l2', C= 0.5)
# X_shuf, Y_shuf = shuffle(df_[cols].as_matrix(), df_[code].as_matrix())
# result = lr.fit(X_shuf,Y_shuf)
#
# # result = logit.fit()
# else:
# for i in sorted_cols:
# print ('has looped to ' + str(i))
# train_cols = list(set(train_cols) | set(['intercept', i]))
# try:
# ori = train_cols[:]
# lr = LogisticRegression(penalty='l2', C=0.5)
# logit = lr.fit(df_[ori],df_[code])
# result = logit.fit()
# train_p = result.pvalues[result.pvalues < 0.05].index.tolist()
# train_params = result.params[result.params > 0].index.tolist()
# train_cols = list(set(train_p) - set(train_params))
# # print result.summary()
# # if len(ori)==len(train_cols) and len(ori)>15 and len(ori)<30:
# # p = result.predict().tolist()
# # Y = df_[code]
# # auc = roc_auc_score(Y, p)
# # print result.summary()
# # print '===================================='
# # print auc
# # if func_check_(result.params) and auc>0.65:
# # vars_dic[num]=[train_cols,auc]
# # print 'the vars can be modeled',auc
# # print len(ori)-1
# # print ori
# # print 'has saved vars'
# # else:
# # continue
# except Exception:
# # print Exception,":",e
# print('some error ')
# train_cols.remove(i)
# error_var.append(i)
# train_p = result.pvalues[result.pvalues < 0.05].index.tolist()
# train_params = result.params[result.params > 0].index.tolist()
# train_cols = list(set(train_p) - set(train_params))
# lr = LogisticRegression(penalty='l2', C=0.5)
# logit = lr.fit( df_[train_cols],df_[code])
# result = logit.fit()
# print(result.summary2())
# # print result.summary2()
# print ('aic:%f' % (float(result.aic)))
# p = result.predict().tolist()
# Y = df_[code]
# auc = roc_auc_score(Y, p)
# # df_['p']=p
# ks_df = cal_ks(result, df_, code, 550, 40)
# # ks_max, df_gp=gb_add_woe(df_,code)
# # print 'max_ks_uncut:' +str(ks_max)
# # detail_p=df_[['p',code]]
# return train_cols,result,vars_dic
# return train_cols, result, vars_dic, ks_df.ix[1, 'describe'], error_var
def pmml(x, Y):
from sklearn2pmml import PMMLPipeline, sklearn2pmml
LR_pipeline = PMMLPipeline([
("classifier", LogisticRegression())
])
# 训练模型
LR_pipeline.fit(x, Y)
sklearn2pmml(LR_pipeline, "LogisticRegression.pmml")
# 导出模型到 RandomForestClassifier_Iris.pmml 文件
# 原建模步骤
def func_stepwise_1(cols, df_, code, report=None, pmml_btn=True,nec_vars=[],base_score=550,double_score=-40):
'''
:param cols: train_cols[list]
:param df_: m_data[pd.df]
:param code: tag_name
:param sort: 是否需要进行排序:TRUE/FALSE
:return: 入参变量
'''
vars_dic = {}
import statsmodels.api as sm
train_cols = ['intercept']
df_['intercept'] = 1
error_var = []
sorted_cols = cols[:]
nec_vars = [i + "_woe" for i in nec_vars if i + "_woe" in df_.columns]
num = 0
if report:
logit = sm.Logit(df_[code], df_[cols])
result = logit.fit()
else:
for i in sorted_cols:
print('has looped to ' + str(i))
train_cols = list(set(train_cols) | set(['intercept', i]))
try:
ori = train_cols[:]
logit = sm.Logit(df_[code], df_[ori])
result = logit.fit()
train_p = result.pvalues[result.pvalues < 0.05].index.tolist()
train_params = result.params[result.params > 0].index.tolist()
train_cols = list(set(train_p) - set(train_params))
# print result.summary()
# if len(ori)==len(train_cols) and len(ori)>15 and len(ori)<30:
# p = result.predict().tolist()
# Y = df_[code]
# auc = roc_auc_score(Y, p)
# print result.summary()
# print '===================================='
# print auc
# if func_check_(result.params) and auc>0.65:
# vars_dic[num]=[train_cols,auc]
# print 'the vars can be modeled',auc
# print len(ori)-1
# print ori
# print 'has saved vars'
# else:
# continue
except Exception:
# print Exception,":",e
print('some error ')
train_cols.remove(i)
error_var.append(i)
#
# train_p = result.pvalues[result.pvalues < 0.05].index.tolist()
# train_params = result.params[result.params > 0].index.tolist()
train_cols = list(set(train_cols)|set(nec_vars)| set(['intercept']))
# lr = LogisticRegression(penalty='l2', C=0.5)
# result = lr.fit(df_[train_cols],df_[code])
logit = sm.Logit(df_[code], df_[train_cols])
result = logit.fit()
if pmml_btn:
pmml(df_[train_cols], df_[code])
print(result.summary2())
print('aic:%f' % (float(result.aic)))
p = result.predict().tolist()
# print(p)
Y = df_[code]
auc = roc_auc_score(Y, p)
# df_['p']=p
ks_df,odds,A,B = cal_ks(result, df_, code, base_score, double_score)
# ks_max, df_gp=gb_add_woe(df_,code)
# print 'max_ks_uncut:' +str(ks_max)
# detail_p=df_[['p',code]]
# return train_cols,result,vars_dic
return train_cols, result, vars_dic, ks_df.ix[1, 'describe'], error_var,odds,A,B
def func_stepwise_sk(cols, df_, code):
'''
:param cols: train_cols[list]
:param df_: m_data[pd.df]
:param code: tag_name
:param sort: 是否需要进行排序:TRUE/FALSE
:return: 入参变量
'''
vars_dic = []
from sklearn import linear_model as lm
lr = lm.LogisticRegression(C=1.0, class_weight=None, dual=False,
fit_intercept=True, intercept_scaling=1,
max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None,
solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
sorted_cols = cols[:]
for i in sorted_cols:
print('has looped to ' + str(i))
train_cols.append(i)
try:
ori = train_cols[:]
X_shuf, Y_shuf = shuffle(df_[ori].as_matrix(), df_[code].as_matirx())
logit = lr.fit(X_shuf, Y_shuf)
result = logit.fit()
train_p = result.pvalues[result.pvalues < 0.03].index.tolist()
train_params = result.params[result.params > 0].index.tolist()
train_cols = list(set(train_p) - set(train_params))
# print result.summary()
# if len(ori)==len(train_cols) and len(ori)>15 and len(ori)<25:
# p = result.predict().tolist()
# Y = df_[code]
# auc = roc_auc_score(Y, p)
# if func_check_(result.params) and auc>0.72:
# vars_dic.append(train_cols)
# print '这些变量可以用来建模啦',auc
# print len(ori)-1
# print ori
# print 'has saved vars'
# else:
# continue
except Exception as e:
print(":", e)
# print 'some error '
train_cols.remove(i)
logit = sm.Logit(df_[code], df_[train_cols])
result = logit.fit()
print(result.summary())
# print result.summary2()
print('aic: ' + str(result.aic))
p = result.predict().tolist()
Y = df_[code]
auc = roc_auc_score(Y, p)
# df_['p']=p
ks_df = cal_ks(result, df_, code, 550, 40)
# ks_max, df_gp=gb_add_woe(df_,code)
# print 'max_ks_uncut:' +str(ks_max)
# detail_p=df_[['p',code]]
# return train_cols,result,vars_dic
return train_cols, result, vars_dic, ks_df.ix[1, 'describe']
def group_p(data, code):
df_rs = data.copy()
list = df_rs.index.tolist()
df_rs.ix[:, 'no'] = list
df_rs['p_bin'] = df_rs['p'][:]
df_rs['good'] = df_rs[code].map(lambda x: func_good(x))
df_rs['bad'] = df_rs[code].map(lambda x: func_bad(x))
b = df_rs.groupby(['p_bin', ])['no', 'good', 'bad'].sum()
df_gp = pd.DataFrame(b)
return df_gp
def gb_add_woe(data, code):
df_gp = group_p(data, code)
df_gp.ix[:, 'pct_default'] = df_gp['bad'] / (df_gp['bad'] + df_gp['good'])
bad_sum = df_gp['bad'].sum()
good_sum = df_gp['good'].sum()
df_gp.ix[:, 'bad_pct'] = df_gp['bad'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'good_pct'] = df_gp['good'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'odds'] = df_gp['good_pct'] - df_gp['bad_pct']
df_gp.ix[:, 'woe'] = np.log(df_gp['good_pct'] / df_gp['bad_pct'])
df_gp.ix[:, 'iv'] = (df_gp['good_pct'] - df_gp['bad_pct']) * df_gp['woe']
bad_cnt = df_gp['bad'].cumsum()
good_cnt = df_gp['good'].cumsum()
df_gp.ix[:, 'bad_cnt'] = bad_cnt
df_gp.ix[:, 'good_cnt'] = good_cnt
df_gp.ix[:, 'b_c_p'] = df_gp['bad_cnt'] / np.array([bad_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'g_c_p'] = df_gp['good_cnt'] / np.array([good_sum for _ in range(len(df_gp))])
df_gp.ix[:, 'ks'] = df_gp['g_c_p'] - df_gp['b_c_p']
ks_max = df_gp['ks'].max()
# print df_gp
return ks_max, df_gp
def func_stepwise(sorted_cols, df_, code):
train_cols = ['intercept']
num = 1
for j in sorted_cols:
# print 'has looped to ' + str(j)
for i in sorted_cols:
train_cols.append(i)
train_cols = list(set(train_cols))
# logit = sm.Logit(df_[train_cols],df_[code])
logit = sm.Logit(df_[code], df_[train_cols])
result = logit.fit()
train_cols = result.pvalues[result.pvalues < 0.05].index.tolist()
try:
train_cols.append(j)
train_cols = list(set(train_cols))
logit = sm.Logit(df_[code], df_[train_cols])
result = logit.fit()
train_cols = result.pvalues[result.pvalues < 0.05].index.tolist()
except:
pass
# print train_cols
logit = sm.Logit(df_[code], df_[train_cols])
result = logit.fit()
# print result.summary()
# print result.summary2()
return train_cols
# col=func_stepwise(coll,M_data,'tag')
def forward_selected(data, response):
"""Linear model designed by forward selection.
Parameters:
-----------
data : pandas DataFrame with all possible predictors and response
response: string, name of response column in data
Returns:
--------
model: an "optimal" fitted statsmodels linear model
with an intercept
selected by forward selection
evaluated by adjusted R-squared
"""
import statsmodels.formula.api as smf
remaining = set(data.columns)
remaining.remove(response)
selected = []
current_score, best_new_score = 0.0, 0.0
while remaining and current_score == best_new_score:
scores_with_candidates = []
for candidate in remaining:
formula = "{} ~ {} + 1".format(response,
' + '.join(selected + [candidate]))
score = smf.ols(formula, data).fit().rsquared_adj
scores_with_candidates.append((score, candidate))
scores_with_candidates.sort()
best_new_score, best_candidate = scores_with_candidates.pop()
if current_score < best_new_score:
remaining.remove(best_candidate)
selected.append(best_candidate)
current_score = best_new_score
formula = "{} ~ {} + 1".format(response,
' + '.join(selected))
model = smf.ols(formula, data).fit()
return model
| 5563cf8b7add73675315d75256a740f9931ea2a0 | [
"SQL",
"Python"
] | 20 | SQL | Kelly0531/Financial-Risk | 06ce24e36cf09733c51000c7d0a6e471954be901 | a20c4da81b96e05efa202aa79193fd4cbeee504e |
refs/heads/master | <repo_name>Apptimate/PingPal-Messenger-Android<file_sep>/src/io/pingpal/models/Person.java
package io.pingpal.models;
/**
* @author <NAME> & <NAME> 23-07-14
*/
public class Person {
@SuppressWarnings("unused")
private static final String TAG = Person.class.getSimpleName();
private String mName;
private int mImageResourceId;
private String mTag;
private String mUserTag = "testTag";
/**
* Use this constructor for user data
* @param facebookId
* @param userTag
* @param name
* @param imageURL
*/
public Person(String tag, String userTag, String name) {
this.mTag = tag;
this.mUserTag = userTag;
this.mName = name;
}
/**
* Use this constructor for friend data
* @param facebookId
* @param userTag
* @param name
* @param imageURL
*/
public Person(String tag, String name) {
this.mTag = tag;
this.mName = name;
}
public String getTag() {
return mTag;
}
public int getImageResourceId() {
return mImageResourceId;
}
public void setImageResourceId(int imageResourceId) {
this.mImageResourceId = imageResourceId;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public String getUserTag() {
return mUserTag;
}
public void setmUserTag(String mUserTag) {
this.mUserTag = mUserTag;
}
}
<file_sep>/src/io/pingpal/abstractclasses/BaseActivity.java
package io.pingpal.abstractclasses;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
public abstract class BaseActivity extends Activity {
public static ImageLoader imageLoader = ImageLoader.getInstance();
}
<file_sep>/src/io/pingpal/models/Message.java
package io.pingpal.models;
import java.util.Date;
/**
* @author <NAME> & <NAME> 22-07-14
*/
public class Message {
private String mSenderTag, mReceiverTag;
private String mMessage;
private Date mTimeStamp;
/**
* AppUser should be false if this message was received from a friend Set to
* true if message was sent by this apps user.
*/
private int mConversationId = 0;
/**
* @param senderTag the facebookId of the contact
* @param message the message text
* @param timeStamp the time of arrival as a long, use Date.getTime()
* @param conversationId the id of the conversation, currently the
* facebookId, will need to change when suppport for groups is
* added
*/
public Message(String senderTag, String message, long timeStamp, int conversationId, long groupId, String receiverTag) {
this.mSenderTag = senderTag;
this.mMessage = message;
this.mTimeStamp = new Date(timeStamp);
this.mReceiverTag = receiverTag;
this.mConversationId = conversationId;
this.mGroupId = groupId;
}
private long mMessageId;
public long getId() {
return mMessageId;
}
public void setId(long id) {
this.mMessageId = id;
}
public Date getDate() {
return mTimeStamp;
}
public long getDateAsLong() {
return mTimeStamp.getTime();
}
public String getDateAsString() {
return mTimeStamp.toString();
}
public String getMessage() {
return mMessage;
}
private boolean mMessageRead = false;
public boolean isMessageRead() {
return mMessageRead;
}
public void setMessageRead(boolean messageRead) {
this.mMessageRead = messageRead;
}
public String getsenderID() {
return mSenderTag;
}
public String getreceiverID(){
return mReceiverTag;
}
/**
* Group ID set to -1 if the message is not part of a group conversation
*/
private long mGroupId = -1;
public long getGroupId() {
return mGroupId;
}
public int getConversationId() {
return mConversationId;
}
public void setConversationId(int conversationId) {
this.mConversationId = conversationId;
}
private String mImageIconName;
public String getImageIconName() {
return mImageIconName;
}
public void setImageIconName(String imageIconName) {
this.mImageIconName = imageIconName;
}
}
<file_sep>/src/io/pingpal/location/DialogDelegate.java
package io.pingpal.location;
import io.pingpal.outbox.Outbox;
import java.util.HashMap;
import java.util.Map;
import android.location.Location;
import android.os.Handler;
import android.util.Log;
class DialogDelegate implements TrackerListenerProtocol {
private Tracker tracker;
Location currentLocation;
private double accuracyMeters;
private double timeoutSeconds;
private String sendTo;
private String sendSeq;
private Handler handler;
private Runnable runnable;
DialogDelegate(String from, String seq, double accurMeters, double durationSeconds) {
sendTo = from;
sendSeq = seq;
if (accurMeters > 0) {
accuracyMeters = accurMeters;
}else{
accuracyMeters = 100;
}
if (durationSeconds > 0) {
timeoutSeconds = durationSeconds;
}else{
timeoutSeconds = 30;
}
tracker = Tracker.getSharedTracker();
tracker.addDelegate(this);
runnable = new Runnable() {
@Override
public void run() {
timeout();
}
};
handler = new Handler();
handler.postDelayed(runnable, (long) (timeoutSeconds * 1000));
}
void stop() {
handler.removeCallbacks(runnable);
tracker = Tracker.getSharedTracker();
tracker.removeDelegate(this);
}
void timeout() {
Log.i("LocationManager", "PositionDialog timedout.");
if (GeoUtil.isLocationOk(currentLocation)) {
sendLocation();
}
else{
Log.i("LocationManager", "PositionDialog timedout. No location could be obtained.");
}
stop();
}
void sendLocation() {
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
double altitude = currentLocation.getAltitude();
float accuracy = currentLocation.getAccuracy();
float course = currentLocation.getBearing();
float speed = currentLocation.getSpeed();
Map<String, Object> locationData = new HashMap<String, Object>();
locationData.put("latitude", latitude);
locationData.put("longitude", longitude);
locationData.put("altitude", altitude);
locationData.put("horizontalAccuracy", accuracy);
locationData.put("verticalAccuracy", accuracy);
locationData.put("course", course);
locationData.put("speed", speed);
long timeStamp = System.currentTimeMillis() / 1000l;
locationData.put("timestamp", timeStamp);
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("location", locationData);
Map<String, Object> options = new HashMap<String, Object>();
options.put("yourseq", sendSeq);
Log.i("LocationManager", "Sending location.");
Outbox.put(sendTo, payload, options);
}
@Override
public void setLocation(Location location) {
if (currentLocation == null) {
currentLocation = location;
} else if (location.getAccuracy() < currentLocation.getAccuracy()) {
currentLocation = location;
}
Log.i("LocationManager", "Accuracy is: " + location.getAccuracy());
if (currentLocation.getAccuracy() <= accuracyMeters) {
sendLocation();
stop();
}
}
}
<file_sep>/src/io/pingpal/fragments/CreateGroupsFragment.java
package io.pingpal.fragments;
import io.pingpal.adapters.GroupFriendsAdapter;
import io.pingpal.database.DatabaseCursorLoader;
import io.pingpal.database.DatabaseHelper;
import io.pingpal.database.FriendsDataSource;
import io.pingpal.messenger.MainActivity;
import io.pingpal.messenger.R;
import io.pingpal.outbox.Outbox;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
/**
* @author <NAME> 18-02-2015
*/
public class CreateGroupsFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnClickListener{
private ListView listView;
private Button createGroupButton;
private EditText editText;
private String userTag;
private List<String> members = new ArrayList<String>();
private Cursor cursor;
/*
* Server http request links. Responses will be in Json format.
*/
public static final String createGroup = "http://ppmapi.com/ppmess/rest/msggroup/creategroup?name=thename&tag=thetag";
public static final String setGroupName = "http://ppmapi.com/ppmess/rest/msggroup/setgroupname?name=thename&tag=thetag";
public static final String removeMember = "http://ppmapi.com/ppmess/rest/msgmember/removemember?name=thename&tag=thetag";
public static final String getGroupName = "http://ppmapi.com/ppmess/rest/msggroup/getgroupname?tag=thetag";
public static final String getGroups = "http://ppmapi.com/ppmess/rest/msgmember/getgroups?name=thename";
public static final String getMembers = "http://ppmapi.com/ppmess/rest/msggroup/getmembers?tag=thetag";
public static final String addMember = "http://ppmapi.com/ppmess/rest/msgmember/addmember?name=thename&tag=thetag";
@SuppressWarnings("unused")
private static final String TAG = CreateGroupsFragment.class.getSimpleName();
/**
* The fragment argument representing the section number for this fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static CreateGroupsFragment newInstance(int sectionNumber) {
CreateGroupsFragment fragment = new CreateGroupsFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_groups_manage, container, false);
listView = (ListView) rootView.findViewById(R.id.group_friends_listview);
createGroupButton = (Button) rootView.findViewById(R.id.create_group_button);
editText = (EditText) rootView.findViewById(R.id.group_editText_name);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide vertical keyboard
in.hideSoftInputFromWindow(v
.getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
}
});
createGroupButton.setOnClickListener(new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
String groupName = editText.getText().toString();
if(groupName.length() > 0){
Map<String, String> groupParams = new HashMap<String, String>();
groupParams.put("group_name", groupName);
new GroupCreateAsync().execute(groupParams);
}
}
});
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userTag = ((MainActivity)getActivity()).getUserTag();
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String userTag = ((MainActivity)getActivity()).getUserTag();
String[] params = new String[] {
userTag
};
return new DatabaseCursorLoader(getActivity(), FriendsDataSource.QUERY_ACTIVE_FRIENDS, params);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
cursor = arg1;
listView.setAdapter(new GroupFriendsAdapter(getActivity(), arg1, this));
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
arg0 = null;
}
class GroupCreateAsync extends AsyncTask<Map<String,String>, String, String>{
@Override
protected String doInBackground(Map<String,String>... params) {
Map<String,String> createParams = params[0];
String groupName = createParams.get("group_name");
String groupTag = Outbox.createUniqueTag();
groupName = CreateGroupsFragment.encodeToUTF8(groupName);
String encGroupTag = CreateGroupsFragment.encodeToUTF8(groupTag);
String URI = createGroup;
URI = URI.replace("thename", groupName);
URI = URI.replace("thetag", encGroupTag);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(URI));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() != HttpStatus.SC_OK){
//Close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return groupTag;
}
@Override
protected void onPostExecute(String theGroupTag) {
super.onPostExecute(theGroupTag);
Toast.makeText(getActivity(), getString(R.string.create_success), Toast.LENGTH_SHORT).show();
//Add user to members list
members.add(userTag);
resetViews();
new AddMembersAsync().execute(theGroupTag);
}
}
class AddMembersAsync extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... params) {
String groupTag = params[0];
String URI;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
//Loop through members, add each to group
for (int i = 0; i < members.size(); i++) {
String memberTag = members.get(i);
String encodedMemberTag = CreateGroupsFragment.encodeToUTF8(memberTag);
String encGroupTag = CreateGroupsFragment.encodeToUTF8(groupTag);
URI = addMember;
URI = URI.replace("thename", encodedMemberTag);
URI = URI.replace("thetag", encGroupTag);
try {
response = httpclient.execute(new HttpGet(URI));
StatusLine statusLine = response.getStatusLine();
response.getEntity().consumeContent();
if(statusLine.getStatusCode() != HttpStatus.SC_OK){
//Close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
else{
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("groupNotifyChanged", groupTag);
payload.put("member", members.get(i));
payload.put("changedTo", "notify");
Outbox.put(members.get(i), payload);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
/**
* Encode a string into UTF-8 format
* @param string
* @return encoded string
*/
public static String encodeToUTF8(String string){
try {
string = URLEncoder.encode(string, "UTF-8");
return string;
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return string;
}
private void resetViews(){
listView.setItemChecked(-1, false);
editText.setText("");
}
@Override
public void onClick(View v) {
int pos = listView.getPositionForView(v);
if(pos != ListView.INVALID_POSITION){
//Find the row with the correct position in the cursor
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int position = cursor.getPosition();
if(position == pos){
break;
}
cursor.moveToNext();
}
String tag = cursor.getString(cursor
.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG));
members.add(tag);
}
}
}
<file_sep>/src/io/pingpal/location/TrackerListenerProtocol.java
package io.pingpal.location;
import android.location.Location;
interface TrackerListenerProtocol {
void setLocation(Location location);
}
<file_sep>/src/io/pingpal/adapters/FriendsListAdapter.java
package io.pingpal.adapters;
import io.pingpal.database.DatabaseHelper;
import io.pingpal.fragments.FacebookFragment;
import io.pingpal.messenger.R;
import io.pingpal.models.Person;
import java.util.concurrent.ExecutionException;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class FriendsListAdapter extends SimpleCursorAdapter {
@SuppressWarnings("unused")
private static final String TAG = FriendsListAdapter.class.getSimpleName();
private LayoutInflater mInflater;
private DisplayImageOptions mImageOptions;
private Cursor mCursor;
private ImageLoader mImageLoader;
public FriendsListAdapter(Context context, Cursor cursor) {
super(context, 0, null, null, null, 0);
this.mCursor = cursor;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
.displayer(new RoundedBitmapDisplayer(90)).build();
mImageLoader = ImageLoader.getInstance();
}
@Override
public int getCount() {
return mCursor.getCount();
}
@Override
public Object getItem(int position) {
mCursor.moveToPosition(position);
Person friend = new Person(mCursor.getString(mCursor
.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG)), DatabaseHelper.COLUMN_TAG,
mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
return friend;
}
@Override
public long getItemId(int position) {
mCursor.moveToPosition(position);
String friendTag = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG));
return Long.parseLong(friendTag.replace("#", ""));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
View rootView = convertView;
if (rootView == null) {
rootView = mInflater.inflate(R.layout.row_friends_layout, parent, false);
holder = buildViewHolder(rootView);
} else {
holder = (ViewHolder)rootView.getTag();
}
buildView(position, holder);
rootView.setTag(holder);
return rootView;
}
/**
* Adds the Friend data to the view stored in the ViewHolder
*
* @param position The position of the view
* @param holder The ViewHolder Object that contains the view
*/
private void buildView(int position, ViewHolder holder) {
mCursor.moveToPosition(position);
String friendID = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG)).replace("#", "");
mImageLoader.displayImage(FacebookFragment.IMG_URL_START + friendID
+ FacebookFragment.IMG_URL_END,
holder.icon, mImageOptions);
mCursor.moveToPosition(position);
holder.nameTextView.setText(mCursor.getString(mCursor
.getColumnIndex(DatabaseHelper.COLUMN_NAME)));
}
/**
* This method executes off the main thread to inflate the requested view
* and add it to a ViewHolder Object
*
* @param rootView the view to be added to the viewHolder
* @return ViewHolder constructed ViewHolder Object
*/
private ViewHolder buildViewHolder(View rootView) {
ViewHolder holder = null;
AsyncTask<View, Void, ViewHolder> task = new AsyncTask<View, Void, ViewHolder>() {
ViewHolder holder = new ViewHolder();
@Override
protected ViewHolder doInBackground(View... params) {
View rootView = params[0];
holder.icon = (ImageView)rootView.findViewById(R.id.icon_friend);
holder.nameTextView = (TextView)rootView.findViewById(R.id.label_friend);
return holder;
}
}.execute(rootView);
try {
holder = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return holder;
}
public static class ViewHolder {
public ImageView icon;
public TextView nameTextView;
}
}
<file_sep>/src/io/pingpal/fragments/GoogleMapsFragment.java
package io.pingpal.fragments;
import io.pingpal.messenger.R;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* @author <NAME> 22-03-2015
*/
public class GoogleMapsFragment extends Fragment {
private Location location;
private GoogleMap map;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
map =((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
MapsInitializer.initialize(getActivity());
if(location != null){
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions marker = new MarkerOptions().position(position);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.ping_marker));
map.addMarker(marker);
// Move the camera to location (instantly)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.map_options, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.normal:
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.satellite:
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.terrain:
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
case R.id.hybrid:
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.normal);
MenuItem item2 = menu.findItem(R.id.satellite);
MenuItem item3 = menu.findItem(R.id.terrain);
MenuItem item4 = menu.findItem(R.id.hybrid);
if(item != null){
item.setVisible(true);
item2.setVisible(true);
item3.setVisible(true);
item4.setVisible(true);
if(map != null){
switch(map.getMapType()){
case GoogleMap.MAP_TYPE_NORMAL:
item.setVisible(false);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
item2.setVisible(false);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
item3.setVisible(false);
break;
case GoogleMap.MAP_TYPE_HYBRID:
item4.setVisible(false);
break;
}
}
else{
item.setVisible(false);
}
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
SupportMapFragment smf = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (smf != null){
//getFragmentManager().beginTransaction().remove(smf).commit();
}
}
public void setLocation(Location location){
this.location = location;
}
}
<file_sep>/src/io/pingpal/database/FriendsDataSource.java
package io.pingpal.database;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import io.pingpal.models.Person;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class FriendsDataSource {
@SuppressWarnings("unused")
private static final String TAG = FriendsDataSource.class.getSimpleName();
public static final int CASE_APP_USER = 0;
public static final int CASE_FACEBOOK_FRIEND = 1;
public static final int CASE_OTHER_FRIEND = 2;
public static final String QUERY_ACTIVE_FRIENDS =
"SELECT " + DatabaseHelper.TABLE_FRIENDS + "." + DatabaseHelper.COLUMN_FRIEND_TAG + ", "
+ DatabaseHelper.COLUMN_NAME
+ " FROM " + DatabaseHelper.TABLE_FRIENDS
+ " JOIN " + DatabaseHelper.TABLE_USERS_FRIENDS
+ " ON " + DatabaseHelper.TABLE_USERS_FRIENDS + "." + DatabaseHelper.COLUMN_FRIEND_TAG
+ " = " + DatabaseHelper.TABLE_FRIENDS + "." + DatabaseHelper.COLUMN_FRIEND_TAG
+ " WHERE " + DatabaseHelper.COLUMN_USER_TAG + " = (?)";
private String[] mAllFriendsColumns = {
"ID", DatabaseHelper.COLUMN_FRIEND_TAG, DatabaseHelper.COLUMN_NAME, DatabaseHelper.COLUMN_PING
};
private DatabaseHelper mDbHelper;
public FriendsDataSource(Context context) {
mDbHelper = new DatabaseHelper(context);
}
private SQLiteDatabase mDb;
public void open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Person getFriend(String friendTag) {
String[] selectionArgs = {
friendTag
};
Person friend = null;
Cursor cursor = mDb.query(DatabaseHelper.TABLE_FRIENDS, mAllFriendsColumns,
DatabaseHelper.COLUMN_FRIEND_TAG + " = ?", selectionArgs, null, null, null, null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
friend = new Person(cursor.getString(1), cursor.getString(2));
}
cursor.close();
return friend;
}
public Person getFriend(int conversationID) {
String[] selectionArgs = {
String.valueOf(conversationID)
};
Person friend = null;
Cursor cursor = mDb.rawQuery(DatabaseHelper.QUERY_FRIEND_BY_CONVERSATION_ID, selectionArgs);
if(cursor.getCount() > 0){
cursor.moveToFirst();
friend = new Person(cursor.getString(0), cursor.getString(1));
}
cursor.close();
return friend;
}
public int getFriendPingAccess(String friendTag) {
String[] selectionArgs = {
friendTag
};
String[] selection = {
DatabaseHelper.COLUMN_PING
};
int pingAccess = -1;
Cursor cursor = mDb.query(DatabaseHelper.TABLE_FRIENDS, selection,
DatabaseHelper.COLUMN_FRIEND_TAG + " = ?", selectionArgs, null, null, null, null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
pingAccess = cursor.getInt(0);
}
cursor.close();;
return pingAccess;
}
public void setFriendPingAccess(String friendTag, int pingAccess) {
String[] selectionArgs = {
friendTag
};
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_PING, pingAccess);
mDb.update(DatabaseHelper.TABLE_FRIENDS, values, DatabaseHelper.COLUMN_FRIEND_TAG + " = ?", selectionArgs);
}
public String addPersonToDB(Person person, int friendCase) {
//ContentValues values;
switch (friendCase) {
case CASE_APP_USER:
Person user = person;
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
final String insertAppUser =
"INSERT INTO " + DatabaseHelper.TABLE_USERS + " ("
+ DatabaseHelper.COLUMN_USER_TAG + ", "
+ DatabaseHelper.COLUMN_TAG + ", "
+ DatabaseHelper.COLUMN_NAME + ", "
+ DatabaseHelper.COLUMN_LAST_LOGIN + ")"
+ " SELECT '"
+ user.getTag() + "', '"
+ user.getUserTag() + "', '"
+ user.getName() + "', "
+ dateFormat.format(date)
+ " WHERE NOT EXISTS ( SELECT 1 FROM "
+ DatabaseHelper.TABLE_USERS + " WHERE " + DatabaseHelper.COLUMN_USER_TAG
+ " = '" + user.getTag() + "')";
mDb.execSQL(insertAppUser);
//Log.v(TAG, "Adding user if not exist: " + user.getTag() + user.getName());
return user.getTag();
case CASE_FACEBOOK_FRIEND:
Person friend = person;
final String insertFacebookFriend =
"INSERT INTO " + DatabaseHelper.TABLE_FRIENDS + " ("
+ DatabaseHelper.COLUMN_FRIEND_TAG + ", "
+ DatabaseHelper.COLUMN_NAME + ", "
+ DatabaseHelper.COLUMN_PING
+ ") SELECT '"
+ friend.getTag() + "', '"
+ friend.getName() + "', "
+ DatabaseHelper.FALSE
+ " WHERE NOT EXISTS ( SELECT 1 FROM "
+ DatabaseHelper.TABLE_FRIENDS + " WHERE "
+ DatabaseHelper.COLUMN_FRIEND_TAG + " = '" + friend.getTag() + "');";
mDb.execSQL(insertFacebookFriend);
//Log.v(TAG, "Inserted friend: " + friend.getTag() + friend.getName());
return friend.getTag();
default:
throw new IllegalArgumentException(
"An invalid friendCase was passed into addFriend() in FriendsDataSource, addFriend() failed!");
}
}
public void addRelation(String userTag, String friendTag){
final String insertUserFriendRelation =
"INSERT INTO " + DatabaseHelper.TABLE_USERS_FRIENDS + " SELECT '"
+ userTag + "', '" + friendTag
+ "' WHERE NOT EXISTS ( SELECT 1 FROM "
+ DatabaseHelper.TABLE_USERS_FRIENDS
+ " WHERE " + DatabaseHelper.COLUMN_USER_TAG + " = '" + userTag
+ "' AND " + DatabaseHelper.COLUMN_FRIEND_TAG + " = '" + friendTag + "')";
mDb.execSQL(insertUserFriendRelation);
}
}
<file_sep>/src/io/pingpal/location/Tracker.java
package io.pingpal.location;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
class Tracker implements TrackerProtocol {
private static Tracker sharedTracker;
private static List<TrackerListenerProtocol> delegates = new ArrayList<TrackerListenerProtocol>();
private static boolean isTracking;
private static LocationManager locationManager;
private final int LOCATION_REFRESH_DISTANCE = 30, LOCATION_REFRESH_TIME = 10000;
static void Setup (Context context){
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(sharedTracker == null){
sharedTracker = new Tracker();
}
}
static Tracker getSharedTracker(){
return sharedTracker;
}
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
Log.i("LocationManager", "Got location");
if (GeoUtil.isLocationOk(location)) {
updateDelegatesWithLocation(location);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
@Override
public void addDelegate(TrackerListenerProtocol delegate) {
delegates.add(delegate);
if (delegates.size() == 1) {
startTracking();
}
}
@Override
public void removeDelegate(TrackerListenerProtocol delegate) {
if (delegates.contains(delegate)) {
delegates.remove(delegate);
}
if (delegates.size() == 0) {
stopTracking();
}
}
boolean isTracking() {
return isTracking;
}
void restartWithDistance(long distance) {
if (isTracking) {
stopTracking();
}
locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), LOCATION_REFRESH_TIME, distance, mLocationListener);
isTracking = true;
}
@Override
public void updateDelegatesWithLocation(Location location) {
for (int i = 0; i < delegates.size(); i++) {
delegates.get(i).setLocation(location);
}
}
@Override
public void stopTracking() {
Log.i("LocationManager", "Stop tracking");
locationManager.removeUpdates(mLocationListener);
isTracking = false;
}
public Location getLastKnownLocation(){
return locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
}
@Override
public void startTracking() {
Log.i("LocationManager", "Start tracking");
/*if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
}
else {
Log.e("LocationManager", "No provider is enabled.");
}*/
locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), false), LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
isTracking = true;
}
}
<file_sep>/src/io/pingpal/fragments/GroupInfoFragment.java
package io.pingpal.fragments;
import io.pingpal.adapters.GroupFriendsAdapter;
import io.pingpal.adapters.GroupMembersAdapter;
import io.pingpal.database.DatabaseCursorLoader;
import io.pingpal.database.DatabaseHelper;
import io.pingpal.database.FriendsDataSource;
import io.pingpal.database.MessagesDataSource;
import io.pingpal.messenger.Keys;
import io.pingpal.messenger.MainActivity;
import io.pingpal.messenger.R;
import io.pingpal.models.CheckBoxFriend;
import io.pingpal.models.Person;
import io.pingpal.outbox.Outbox;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author <NAME> 03-03-2015
*/
public class GroupInfoFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnClickListener{
private ListView membersListView, friendAddListView;
private Button applyButton;
private Context context;
private String groupTag;
private Cursor cursor;
private boolean userHasQuit;
//Keeps track of which friends/members have been selected
private List<String> membersTags = new ArrayList<String>(), friendsTags = new ArrayList<String>();
//Data for GroupMembersAdapter
List<CheckBoxFriend> membersList = new ArrayList<CheckBoxFriend>();
public static GroupInfoFragment newInstance(String groupTag) {
GroupInfoFragment fragment = new GroupInfoFragment();
Bundle args = new Bundle();
args.putString("group_tag", groupTag);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_group_info, container, false);
membersListView = (ListView) rootView.findViewById(R.id.group_members_listview);
friendAddListView = (ListView) rootView.findViewById(R.id.group_addfriends_listview);
applyButton = (Button) rootView.findViewById(R.id.group_removemember_btn);
applyButton.setOnClickListener(new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
//Remove chosen members from group
new RemoveMembersAsync().execute(membersTags);
membersTags = new ArrayList<String>();
//Add chosen friends to group
new AddMembersAsync().execute(friendsTags);
friendsTags = new ArrayList<String>();
}
});
context = getActivity().getApplicationContext();
groupTag = getArguments().getString("group_tag");
new GetGroupMembers().execute(groupTag);
getLoaderManager().initLoader(0, null, this);
//Firstimetooltip
final SharedPreferences prefs = getActivity().getPreferences(Activity.MODE_PRIVATE);
boolean isFirstTime = prefs.getBoolean(Keys.Preferences.FIRST_GROUP_INFO, true);
if(isFirstTime){
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.tips))
.setMessage(getString(R.string.groupinfo_tip))
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Now user har seen tooltip
Editor edit = prefs.edit();
edit.putBoolean(Keys.Preferences.FIRST_GROUP_INFO, false);
edit.apply();
}
})
.setIcon(R.drawable.ic_ping_alert)
.show();
}
return rootView;
}
public class GetGroupMembers extends AsyncTask<String, Void, List<String>> {
@Override
protected List<String> doInBackground(String... params) {
String groupTag = params[0];
groupTag = CreateGroupsFragment.encodeToUTF8(groupTag);
String URI = CreateGroupsFragment.getMembers;
URI = URI.replace("thetag", groupTag);
List<String> members = new ArrayList<String>();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(URI));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
//Nested hashmap
@SuppressWarnings("unchecked")
Map<String, ArrayList<Map<String, String>>> result =
new ObjectMapper().readValue(responseString, HashMap.class);
ArrayList<Map<String, String>> list = result.get("response");
for (int i = 0; i < list.size(); i++) {
String memberTag = list.get(i).get("name");
members.add(memberTag);
}
return members;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
//add result (membertags) into list along with names
if (result.size() > 0) {
String userTag = ((MainActivity) getActivity()).getUserTag();
for (String memberTag : result) {
String name = "";
// check if user
if (userTag.equals(memberTag)) {
SharedPreferences sp = getActivity().getPreferences(
Context.MODE_PRIVATE);
String userName = sp.getString("user_name", "");
name = userName;
} else {
// Get name of member from db
FriendsDataSource db = new FriendsDataSource(context);
db.open();
Person friend = db.getFriend(memberTag);
db.close();
if (friend != null) {
name = friend.getName();
}
}
membersList.add(new CheckBoxFriend(name, memberTag));
}
membersListView.setAdapter(new GroupMembersAdapter(context,
membersList, GroupInfoFragment.this));
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String userTag = ((MainActivity)getActivity()).getUserTag();
String[] params = new String[] {
userTag
};
return new DatabaseCursorLoader(getActivity(), FriendsDataSource.QUERY_ACTIVE_FRIENDS, params);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
cursor = arg1;
friendAddListView.setAdapter(new GroupFriendsAdapter(context, arg1, this));
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
arg0 = null;
}
class RemoveMembersAsync extends AsyncTask<List<String>, String, Integer>{
@Override
protected Integer doInBackground(List<String>... params) {
List<String> memberTags = params[0];
String URI;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
//Loop through members, remove each from group
for (int i = 0; i < memberTags.size(); i++) {
URI = CreateGroupsFragment.removeMember;
String encodedMemberTag = CreateGroupsFragment.encodeToUTF8(memberTags.get(i));
String encodedGroupTag = CreateGroupsFragment.encodeToUTF8(groupTag);
URI = URI.replace("thename", encodedMemberTag);
URI = URI.replace("thetag", encodedGroupTag);
try {
response = httpclient.execute(new HttpGet(URI));
StatusLine statusLine = response.getStatusLine();
response.getEntity().consumeContent();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
//Let friend know that he is removed from the group (Mohaha)
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("removedFromGroup", groupTag);
Outbox.put(memberTags.get(i), payload);
payload = new HashMap<String, Object>();
payload.put("groupUpdated", groupTag);
Outbox.put(groupTag, payload);
}
else {
//Close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
//If user is removing self from group, remove group from db
String userTag = ((MainActivity)getActivity()).getUserTag();
if (memberTags.get(i).equals(userTag)) {
MessagesDataSource mMessageDb = new MessagesDataSource(context);
mMessageDb.open();
mMessageDb.removeGroup(groupTag);
mMessageDb.close();
//stop listening
Outbox.unsubscribeTag(userTag, groupTag);
userHasQuit = true;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
class AddMembersAsync extends AsyncTask<List<String>, String, Void>{
@Override
protected Void doInBackground(List<String>... params) {
List<String> friendTags = params[0];
String URI;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
//Loop through members, add each to group
for (int i = 0; i < friendTags.size(); i++) {
String memberTag = friendTags.get(i);
String encodedMemberTag = CreateGroupsFragment.encodeToUTF8(memberTag);
String encGroupTag = CreateGroupsFragment.encodeToUTF8(groupTag);
URI = CreateGroupsFragment.addMember;
URI = URI.replace("thename", encodedMemberTag);
URI = URI.replace("thetag", encGroupTag);
try {
response = httpclient.execute(new HttpGet(URI));
StatusLine statusLine = response.getStatusLine();
response.getEntity().consumeContent();
if(statusLine.getStatusCode() != HttpStatus.SC_OK){
//Close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
else {
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put("groupNotifyChanged", groupTag);
payload.put("member", memberTag);
payload.put("changedTo", "notify");
Outbox.put(memberTag, payload);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(userHasQuit){
((MainActivity)getActivity()).switchFragment(MainActivity.CASE_GROUP);
}
else {
((MainActivity)getActivity()).onGroupInfoSelected(groupTag);
}
}
}
@Override
public void onClick(View v) {
int pos = -1;
//Gets the listview that the checkbox is in
ListView listView = (ListView) v.getParent().getParent();
//Gets the positon of the checkbox in the listview
pos = listView.getPositionForView(v);
if(pos != ListView.INVALID_POSITION){
CheckBox checkBox = (CheckBox) v;
/*
* The membersListView uses memberslist in its adapter
*/
if(listView.equals(membersListView)){
CheckBoxFriend checkboxfriend = membersList.get(pos);
if(checkBox.isChecked()){
membersTags.add(checkboxfriend.getTag());
}
else{
membersTags.remove(checkboxfriend.getTag());
}
}
/*
* The friendAddListView uses cursor in its adapter
*/
else if(listView.equals(friendAddListView)){
//Find the row with the correct position in the cursor
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
if(cursor.getPosition() == pos){
break;
}
cursor.moveToNext();
}
String tag = cursor.getString(cursor
.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG));
if(checkBox.isChecked()){
friendsTags.add(tag);
}
else{
friendsTags.remove(tag);
}
}
}
}
}
<file_sep>/README.md
# Read Me - PingPal Android Messenger
## Summary
This repository is for the Android version of the PingPal Messenger application. This project is an eclipse project.
## Description
PingPal messenger is a privacy protected group chat app with a positioning twist.
Connect with your Facebook friends and chat one-on-one or in groups.
But the best part is that you can check where they are right now. No tracking, just ask and answer.
We call that you "Ping" them. You can even have the app answer automatically where you are,
and that's a good thing when you for instance lost someone and they don't answer their phone.
You can even Ping a group of friends if you're out partying or skiing and get separated from them.
No tracking or stalking! You are in control over who can ping you!
PingPal Messenger is built upon the Apptimate Secure Communication and Positioning as a Service platform,
where no data is stored on their servers, only in your and your friends phones.
No central data that can be hacked and leaked!
## Download on Google Play Store
https://play.google.com/store/apps/details?id=io.pingpal.messenger
**App Version:** 1.0.3
## IDE Details
**IDE:** Eclipse
**Version:** Luna Release (4.4.0)
You will need to download and open the [Facebook Android SDK](https://developers.facebook.com/docs/android/getting-started#install) in Eclipse
You may need to install the Android Development Toolkit plugin.
## Android Details
**Android Version:** 4.0
**Minimum SDK Version:** 15
**Target SDK Version:** 20
**JDK:** 1.6
Thanks to [Universal Image Loader](https://github.com/nostra13/Android-Universal-Image-Loader)
<file_sep>/src/io/pingpal/adapters/EmoticonAdapter.java
package io.pingpal.adapters;
import java.util.ArrayList;
import java.util.List;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class EmoticonAdapter extends BaseAdapter {
private Context mContext;
public EmoticonAdapter(Context c, TypedArray imageArray) {
mContext = c;
for(int i = 0; i < imageArray.length(); i++){
thumbIds.add(imageArray.getResourceId(i,0));
}
}
public int getCount() {
return thumbIds.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return thumbIds.get(position);
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 80, mContext.getResources().getDisplayMetrics());
imageView.setLayoutParams(new GridView.LayoutParams(px, px));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
//imageView.setPadding(24, 24, 24, 24);
} else {
imageView = (ImageView) convertView;
}
ImageLoader.getInstance().displayImage("drawable://" + thumbIds.get(position), imageView);
return imageView;
}
// references to our images
private List<Integer> thumbIds = new ArrayList<Integer>();
}
<file_sep>/src/io/pingpal/adapters/GroupFriendsAdapter.java
package io.pingpal.adapters;
import io.pingpal.database.DatabaseHelper;
import io.pingpal.fragments.FacebookFragment;
import io.pingpal.messenger.R;
import io.pingpal.models.CheckBoxFriend;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
public class GroupFriendsAdapter extends SimpleCursorAdapter{
@SuppressWarnings("unused")
private static final String TAG = GroupFriendsAdapter.class.getSimpleName();
private Cursor mCursor;
private LayoutInflater mInflater;
private DisplayImageOptions mImageOptions;
private Fragment fragment;
//Used to keep track of the selected friends
private List<CheckBoxFriend> checkedFriends = new ArrayList<CheckBoxFriend>();
public GroupFriendsAdapter(Context context, Cursor cursor, Fragment fragment) {
super(context, 0, null, null, null, 0);
this.mCursor = cursor;
this.fragment = fragment;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
.displayer(new RoundedBitmapDisplayer(90)).build();
//Save cursor data to checkedFriends list
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
String name = mCursor.getString(mCursor
.getColumnIndex(DatabaseHelper.COLUMN_NAME));
String tag = mCursor.getString(mCursor
.getColumnIndex(DatabaseHelper.COLUMN_FRIEND_TAG));
checkedFriends.add(new CheckBoxFriend(name, tag));
cursor.moveToNext();
}
}
@Override
public int getCount() {
return mCursor.getCount();
}
/**
* Adds the Conversation data to the view stored in the ViewHolder
*
* @param position The position of the view
* @param holder The ViewHolder Object that contains the view
*/
private void buildView(final int position, ViewHolder holder) {
mCursor.moveToPosition(position);
CheckBoxFriend friendCheck = checkedFriends.get(position);
String id = friendCheck.getTag().replace("#", "");
ImageLoader.getInstance().displayImage(
FacebookFragment.IMG_URL_START + id
+ FacebookFragment.IMG_URL_END, holder.icon, mImageOptions);
holder.nameTextView.setText(friendCheck.getName());
holder.checkBox.setOnClickListener((OnClickListener) fragment);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkedFriends.get(position).setSelected(isChecked);
}
});
holder.checkBox.setChecked(friendCheck.isSelected());
holder.checkBox.setTag(friendCheck);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_group_friend_layout, parent, false);
holder = buildViewHolder(convertView);
} else {
holder = (ViewHolder)convertView.getTag();
}
buildView(position, holder);
convertView.setTag(holder);
return convertView;
}
/**
* This method executes off the main thread to inflate the requested view
* and add it to a ViewHolder Object
*
* @param rootView the view to be added to the viewHolder
* @return ViewHolder constructed ViewHolder Object
*/
private ViewHolder buildViewHolder(View rootView) {
ViewHolder holder = null;
AsyncTask<View, Void, ViewHolder> task = new AsyncTask<View, Void, ViewHolder>() {
@Override
protected ViewHolder doInBackground(View... params) {
ViewHolder holder = new ViewHolder();
View rootView = params[0];
holder.icon = (ImageView)rootView.findViewById(R.id.group_friend_imageview);
holder.nameTextView = (TextView)rootView.findViewById(R.id.group_friend_name);
holder.checkBox = (CheckBox)rootView.findViewById(R.id.group_friend_checkbox);
return holder;
}
}.execute(rootView);
try {
holder = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return holder;
}
/**
* A container class used to store inflated views.
*/
public static class ViewHolder {
public ImageView icon;
public TextView nameTextView;
public CheckBox checkBox;
}
}
<file_sep>/src/io/pingpal/fragments/FacebookFragment.java
package io.pingpal.fragments;
import io.pingpal.abstractclasses.BaseActivity;
import io.pingpal.database.FriendsDataSource;
import io.pingpal.messenger.Communications;
import io.pingpal.messenger.Keys;
import io.pingpal.messenger.MainActivity;
import io.pingpal.messenger.R;
import io.pingpal.models.Person;
import io.pingpal.outbox.Outbox;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
/**
* @author <NAME> & <NAME> 22-07-2014
*/
public class FacebookFragment extends Fragment {
/**
* Use this in conjunction with IMG_URL_END to build a full URL with which
* you can download a users profile picture. The format is IMG_URL_START +
* Facebook ID + IMG_URL_END;
*/
public static final String IMG_URL_START = "https://graph.facebook.com/";
/**
* Use this in conjunction with IMG_URL_START to build a full URL with which
* you can download a users profile picture. The format is IMG_URL_START +
* Facebook ID + IMG_URL_END;
*/
public static final String IMG_URL_END = "/picture?type=normal";
public static final String IMG_URL_END_LARGE = "/picture?type=large";
public static final String FACEBOOK_NAMES = "facebook_names";
public static final String FACEBOOK_IDS = "facebook_ids";
public static final String FACEBOOK_IMAGE_URLS = "facebook_image_paths";
public static final String IMAGE_CACHE_DIRECTORY = "AppDir/cache/images";
/**
* The fragment argument representing the section number for this fragment.
* TODO: Move Facebook code to Facebook class, call from Communications
* class
*/
private static final String ARG_SECTION_NUMBER = "section_number";
@SuppressWarnings("unused")
private static final String TAG = FacebookFragment.class.getSimpleName();
private String userTag;
//private static final int FACEBOOK_LOADER = 2;
private int viewRotation = -13;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static FacebookFragment newInstance(int sectionNumber) {
FacebookFragment fragment = new FacebookFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if(!session.isOpened()){
onSessionStateChange(session, state, exception);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
if(!((MainActivity)getActivity()).isLoggedIn()){
getActivity().getActionBar().hide();
}
// mComms = (Communications)
// getArguments().getSerializable(Communications.KEY_COMMUNICATIONS);
// checkMessagesDb();
userTag = ((MainActivity)getActivity()).getUserTag();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
if(!((MainActivity)getActivity()).isLoggedIn()){
onSessionStateChange(session, session.getState(), null);
}
}
uiHelper.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private TextView mUserNameLbl;
private TextView mWelcomeText;
private ImageView mUserImg, mUserImgShadow;
private ImageView mWelcomeImage, mLayerImage;
private static final String[] PERMISSIONS = new String[] {
"public_profile", "email", "user_friends"
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
mUserImg = (ImageView)rootView.findViewById(R.id.icon_facebook_fragment);
mUserImgShadow = (ImageView)rootView.findViewById(R.id.icon_shadow);
mUserNameLbl = (TextView)rootView.findViewById(R.id.label_name_facebook_fragment);
mWelcomeImage = (ImageView)rootView.findViewById(R.id.welcome_imageview);
mLayerImage = (ImageView)rootView.findViewById(R.id.welcome_layer);
mWelcomeText = (TextView)rootView.findViewById(R.id.welcome_text);
BaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()
.getBaseContext()));
ImageLoader.getInstance().displayImage( "drawable://" + R.drawable.top_image,
mWelcomeImage);
if(((MainActivity)getActivity()).isLoggedIn()){
SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
String userName = sp.getString("user_name", "");
String userID = userTag.replace("#", "");
ImageLoader.getInstance().displayImage(IMG_URL_START + userID + IMG_URL_END_LARGE,
mUserImg, mImageOptions);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.icon_back_white,
mUserImgShadow, mImageOptions);
mWelcomeText.setText(R.string.welcome_text);
mUserNameLbl.setText(getString(R.string.hello) + "\r\n" + userName + "!");
mUserNameLbl.setRotation(viewRotation);
mLayerImage.setVisibility(View.GONE);
mUserImg.setRotation(viewRotation);
}
else{
mLayerImage.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage( "drawable://" + R.drawable.ping_thumbs_up_h100,
mUserImg);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.icon_back_blue,
mUserImgShadow, mImageOptions);
mUserImg.setRotation(viewRotation);
ImageLoader.getInstance().displayImage( "drawable://" + R.drawable.layer_image,
mLayerImage);
}
// Start Facebook Login
LoginButton authButton = (LoginButton)rootView.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(PERMISSIONS);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
private Communications mComms;
/**
* Verifies the Facebook is open, and saves the user profile and friends
* list
*
* @param session
* @param state
* @param exception
*/
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
saveAppUserProfile(session);
getActivity().getActionBar().show();
mLayerImage.setVisibility(View.GONE);
String test = getString(R.string.loggedin_text) + "\r\n" + "\u27A1 \ud83d\udc46 " ;
mWelcomeText.setText(test);
} else if (state.isClosed()) {
//Log.v(TAG, "Logged out...");
SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(Keys.Preferences.LOGGED_IN, false);
editor.commit();
getActivity().getActionBar().hide();
mLayerImage.setVisibility(View.VISIBLE);
mWelcomeText.setText(R.string.welcome_text);
mComms = ((MainActivity)getActivity()).getCommunications();
mComms.resetComms();
ImageLoader.getInstance().displayImage( "drawable://" + R.drawable.ping_thumbs_up_h100,
mUserImg);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.icon_back_blue,
mUserImgShadow, mImageOptions);
mUserImg.setRotation(viewRotation);
mUserNameLbl.setText("");
//Temporary
ImageLoader.getInstance().displayImage( "drawable://" + R.drawable.layer_image,
mLayerImage);
}
}
private DisplayImageOptions mImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).displayer(new RoundedBitmapDisplayer(180))
.build();
/**
* Requests a GraphUser object for the application user from the Facebook
* Graph API and saves the result to the database.
*
* @param session
*/
private void saveAppUserProfile(final Session session) {
//Log.v(TAG, "Logged in...");
//Log.v(TAG, "Requesting profile information...");
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
//Log.v(TAG, "USER DETAILS: ");
//Log.v(TAG, user.getFirstName());
//Log.v(TAG, user.getLastName());
//Log.v(TAG, user.getId());
//Save user info
SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
userTag = "#" + user.getId();
editor.putString(Keys.Preferences.USER_TAG, userTag);
editor.putString(Keys.Preferences.USER_NAME, user.getFirstName());
editor.putBoolean(Keys.Preferences.LOGGED_IN, true);
editor.commit();
if (mComms == null) {
mComms = ((MainActivity)getActivity()).getCommunications();
}
mComms.setupApptimateOutbox();
mUserNameLbl.setText(getString(R.string.hello) + "\r\n" + user.getFirstName() + "!");
mUserNameLbl.setRotation(viewRotation);
ImageLoader.getInstance().displayImage(IMG_URL_START + user.getId() + IMG_URL_END_LARGE,
mUserImg, mImageOptions);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.icon_back_white,
mUserImgShadow, mImageOptions);
mUserImg.setRotation(viewRotation);
FriendsDataSource db = new FriendsDataSource(getActivity());
db.open();
Person mUser = new Person(userTag, Outbox.hashIfTag(userTag), user.getFirstName());
db.addPersonToDB(mUser, FriendsDataSource.CASE_APP_USER);
db.close();
saveFacebookFriends(session);
}
}).executeAsync();
}
private ArrayList<String> imageURLs = new ArrayList<String>();
private ArrayList<String> facebookIds = new ArrayList<String>();
private ArrayList<String> names = new ArrayList<String>();
/**
* Gets a list of the application users Facebook friends and adds them to
* the database or modifies their records with new data if any changes have
* occurred since the last check
*
* @param session
*/
private void saveFacebookFriends(Session session) {
//Log.v(TAG, "requesting friend inforamtion...");
new Request(session, "/me/friends", null, HttpMethod.GET, new Request.Callback() {
@Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject dataSummary = graphObject.getInnerJSONObject();
addFriendsToDatabase(dataSummary);
}
/**
* Saves the application users friend information to the local
* database
*
* @param dataSummary The data returned from the Facebook Graph API
*/
private void addFriendsToDatabase(JSONObject dataSummary) {
try {
JSONArray data = dataSummary.getJSONArray("data");
FriendsDataSource db = new FriendsDataSource(getActivity());
db.open();
for (int i = 0; i < data.length(); i++) {
String friendTag = "#" + data.getJSONObject(i).getString("id");
String name = data.getJSONObject(i).getString("name");
//Log.v(TAG, "FRIEND: ");
//Log.v(TAG, "String Tag: " + friendTag);
//Log.v(TAG, "Name: " + name);
//Log.v(TAG, "Friend to id: " + userTag);
db.addPersonToDB(new Person(friendTag, name), FriendsDataSource.CASE_FACEBOOK_FRIEND);
db.addRelation(userTag, friendTag);
imageURLs.add(IMG_URL_START + data.getJSONObject(i).getString("id")
+ IMG_URL_END);
facebookIds.add(data.getJSONObject(i).getString("id"));
names.add(data.getJSONObject(i).getString("name"));
}
db.close();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
}
}
<file_sep>/src/io/pingpal/messenger/MainActivity.java
package io.pingpal.messenger;
import io.pingpal.database.FriendsDataSource;
import io.pingpal.database.MessagesDataSource;
import io.pingpal.fragments.ConversationFragment;
import io.pingpal.fragments.ConversationListFragment;
import io.pingpal.fragments.CreateGroupsFragment;
import io.pingpal.fragments.FacebookFragment;
import io.pingpal.fragments.FriendsFragment;
import io.pingpal.fragments.GoogleMapsFragment;
import io.pingpal.fragments.GroupInfoFragment;
import io.pingpal.fragments.GroupsFragment;
import io.pingpal.fragments.NavigationDrawerFragment;
import io.pingpal.fragments.SettingsFragment;
import io.pingpal.location.Manager;
import io.pingpal.outbox.Outbox;
import java.util.Map;
import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/**
* @author <NAME> & <NAME> 21-07-14
*/
public class MainActivity extends FragmentActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks,
ConversationListFragment.ConversationSelectedCallbacks,
FriendsFragment.FriendSelectedCallbacks, ActionBar.OnNavigationListener {
public static final int CASE_CONVERSATION_LIST = 0,
CASE_FRIENDS = 1,
CASE_GROUP = 2,
CASE_GROUP_MANAGE = 3,
CASE_FACEBOOK = 4,
CASE_SETTINGS = 5;
@SuppressWarnings("unused")
private static final String TAG = MainActivity.class.getSimpleName();
/**
* The fragment argument representing the section a Fragment fragmentshould
* be placed in
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String EXTRA_MESSAGE = "message";
public static final String EXTRA_FROM = "from";
public static final String PROPERTY_REG_ID = "registration_id";
private NavigationDrawerFragment mNavigationDrawerFragment;
private String deviceTag;
private Communications mComms;
private ConversationFragment mConversationFragment;
private boolean mConversationActive = false;
/**
* Used to store the last screen title. For use in
* {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private String notificationId;
private boolean notificationReceived = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout)findViewById(R.id.drawer_layout));
mComms = new Communications(this);
getFriendIdFromIntent();
Manager.Setup(getApplicationContext());
Manager.AccessHandler accessHandler = new Manager.AccessHandler() {
@Override
public void isItOkToProced(final Map<String, Object> payload,
final Map<String, Object> options, final Callback callback) {
//Get from tag
String fromTag = (String) options.get("from");
FriendsDataSource db = new FriendsDataSource(MainActivity.this);
int pingAccess;
String name = "";
//Check if ping is from user (group ping)
if(fromTag.equals(getUserTag())){
pingAccess = 2; //Don't allow/Ignore
}
else{
//Get name using tag
db.open();
name = db.getFriend(fromTag).getName();
//Get pingaccess for friend
pingAccess = db.getFriendPingAccess(fromTag);
}
db.close();
switch (pingAccess) {
case 0: //Ask
new AlertDialog.Builder(MainActivity.this)
.setTitle(getString(R.string.location_request))
.setMessage(name + " " + getString(R.string.wants_location))
.setPositiveButton(R.string.allow,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
callback.call(payload, options,
callback);
}
})
.setNegativeButton(R.string.not_allow,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).setIcon(R.drawable.ic_ping_alert).show();
break;
case 1: //Allow
callback.call(payload, options,
callback);
break;
case 2:
//Don't allow
break;
}
}
};
Manager.setAccesshandler(accessHandler);
}
/**
* Checks an Intent for bundled extras and extracts data to class members
*/
private void getFriendIdFromIntent() {
Intent intent = getIntent();
Bundle extras = null;
String from = null;
if (intent != null) {
extras = intent.getExtras();
} else {
return;
}
if (extras != null) {
from = extras.getString(EXTRA_FROM);
} else {
return;
}
if (from != null) {
notificationId = from;
notificationReceived = true;
} else {
return;
}
}
@Override
public void onResume() {
super.onResume();
mComms.checkPlayServices();
if(isLoggedIn()){
//Log.v(TAG, "Starting outbox");
mComms.setupApptimateOutbox();
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
String startTicket = sp.getString("ticket", "1");
Outbox.startHistory(startTicket , new Outbox.Callback() {
public void call(Throwable error, Object... args) {
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("ticket", (String) args[0]);
editor.commit();
}
});
}
if (notificationReceived) {
//Create conversation if not exist
int conversationId = getConversationID(notificationId);
onConversationSelected(conversationId);
notificationReceived = false;
}
initializeImageLoader();
}
private void initializeImageLoader() {
if (!ImageLoader.getInstance().isInited()) {
ImageLoaderConfiguration.Builder configBuilder = new ImageLoaderConfiguration.Builder(
this);
ImageLoaderConfiguration config = configBuilder.build();
ImageLoader.getInstance().init(config);
}
}
@Override
public void onNavigationDrawerItemSelected(int position) {
switchFragment(position);
}
public void switchFragment(int position) {
// update the main content by replacing fragments
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//Log.v(TAG, "Selected Position: " + position);
switch (position) {
case CASE_CONVERSATION_LIST:
fragmentTransaction.replace(R.id.container_main,
ConversationListFragment.newInstance(position + 1));
mConversationActive = false;
break;
case CASE_FRIENDS:
fragmentTransaction.replace(R.id.container_main,
FriendsFragment.newInstance(position + 1));
mConversationActive = false;
break;
case CASE_GROUP:
fragmentTransaction.replace(R.id.container_main,
GroupsFragment.newInstance(position + 1));
mConversationActive = false;
break;
case CASE_GROUP_MANAGE:
fragmentTransaction.replace(R.id.container_main,
CreateGroupsFragment.newInstance(position + 1));
mConversationActive = false;
break;
case CASE_FACEBOOK:
fragmentTransaction.replace(R.id.container_main,
FacebookFragment.newInstance(position + 1));
mConversationActive = false;
break;
case CASE_SETTINGS:
fragmentTransaction.replace(R.id.container_main,
SettingsFragment.newInstance(position + 1));
mConversationActive = false;
break;
}
fragmentTransaction.commit();
}
/**
* Update the ActionBar title on selection of an option from the navigation
* drawer
*
* @param number
*/
public void onSectionAttached(int number) {
switch (number) {
// TODO: Implement constants here
case 1:
mTitle = getString(R.string.title_messages);
break;
case 2:
mTitle = getString(R.string.title_friends);
break;
case 3:
mTitle = getString(R.string.title_groups);
break;
case 4:
mTitle = getString(R.string.title_groups_manage);
break;
case 5:
mTitle = getString(R.string.title_facebook);
break;
case 6:
mTitle = getString(R.string.title_contacts);
break;
case 7:
mTitle = getString(R.string.title_settings);
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
//so not to change conversation name
if(!mConversationActive){
actionBar.setTitle(mTitle);
}
actionBar.setDisplayShowCustomEnabled(true);
View view = LayoutInflater.from(actionBar.getThemedContext()).inflate(
R.layout.action_bar_custom, null);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
Button btn = (Button)view.findViewById(R.id.btn_new_msg);
buildNewMessageMenu(btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
newMessageMenu.show();
}
});
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL);
actionBar.setCustomView(view, lp);
}
PopupMenu newMessageMenu;
private void buildNewMessageMenu(Button btn) {
//View btnNewMsg = findViewById(R.id.btn_new_msg);
newMessageMenu = new PopupMenu(getApplicationContext(), btn);
MenuInflater inflater = newMessageMenu.getMenuInflater();
inflater.inflate(R.menu.new_message_options, newMessageMenu.getMenu());
newMessageMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.message:
switchFragment(CASE_FRIENDS);
break;
case R.id.message_group:
switchFragment(CASE_GROUP);
break;
}
return false;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO: Implement Options Menu
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
getActionBar().setTitle(getString(R.string.title_settings));
switchFragment(CASE_SETTINGS);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConversationSelected(int conversationId) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
mConversationFragment = ConversationFragment.newInstance((int) conversationId, ConversationFragment.ConversationType.SINGLE_CONVERSATION);
fragmentTransaction.replace(R.id.container_main, mConversationFragment)
.addToBackStack(ConversationListFragment.class.getSimpleName()).commit();
mConversationActive = true;
}
public void onMapSelected(Location location) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
GoogleMapsFragment mapFragment = new GoogleMapsFragment();
mapFragment.setLocation(location);
fragmentTransaction.replace(R.id.container_main, mapFragment)
.addToBackStack(GoogleMapsFragment.class.getSimpleName()).commit();
}
public void onGroupInfoSelected(String groupTag) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_main, GroupInfoFragment.newInstance(groupTag))
.addToBackStack(GroupInfoFragment.class.getSimpleName()).commit();
}
public void onGroupSelected(int groupID) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
mConversationFragment = ConversationFragment.newInstance(groupID, ConversationFragment.ConversationType.GROUP_CONVERSATION);
fragmentTransaction.replace(R.id.container_main, mConversationFragment)
.addToBackStack(ConversationListFragment.class.getSimpleName()).commit();
mConversationActive = true;
}
public Communications getCommunications() {
return mComms;
}
@Override
public void onFriendSelected(int conversationID) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
mConversationFragment = ConversationFragment.newInstance(conversationID, ConversationFragment.ConversationType.SINGLE_CONVERSATION);
fragmentTransaction.replace(R.id.container_main, mConversationFragment)
.addToBackStack(ConversationListFragment.class.getSimpleName()).commit();
mConversationActive = true;
}
public void updateConversationFragment() {
if (mConversationActive) {
mConversationFragment.updateMessagesListView();
}
}
public String getDeviceTag() {
return deviceTag;
}
public void setDeviceTag(String deviceTag) {
this.deviceTag = deviceTag;
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Toast.makeText(this, "You Selected: " + itemPosition, Toast.LENGTH_SHORT).show();
return false;
}
/**
* Gets the conversation id for the conversation between the user and the selected friend.
* If no conversation is found, it will be created.
*
* @param friendTag ID of the friend of the conversation
* @return The conversation ID
*/
public int getConversationID(String friendTag){
String userTag = getUserTag();
MessagesDataSource db = new MessagesDataSource(this);
db.open();
int conversationID = db.addConversation(userTag, friendTag);
db.close();
return conversationID;
}
public String getUserTag(){
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
return sp.getString(Keys.Preferences.USER_TAG, "");
}
/**
* Returns whether or not user is logged in.
* @return true if user is logged in
*/
public boolean isLoggedIn(){
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
return sp.getBoolean(Keys.Preferences.LOGGED_IN, false);
}
}
<file_sep>/src/io/pingpal/fragments/ConversationListFragment.java
package io.pingpal.fragments;
import io.pingpal.adapters.ConversationListAdapter;
import io.pingpal.database.DatabaseCursorLoader;
import io.pingpal.database.DatabaseHelper;
import io.pingpal.messenger.MainActivity;
import io.pingpal.messenger.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ConversationListFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = ConversationListFragment.class.getSimpleName();
private static final int CONVERSATION_LIST_LOADER = 1;
public static ConversationListFragment newInstance(int sectionNumber) {
ConversationListFragment fragment = new ConversationListFragment();
Bundle args = new Bundle();
args.putInt(MainActivity.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(CONVERSATION_LIST_LOADER, null, this);
}
private ListView mConversationsListView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_conversation_list, container, false);
mConversationsListView = (ListView)rootView.findViewById(R.id.conversations_listview);
mConversationsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.v(TAG, "You selected conversation " + id);
String friendTag = "#" + id;
int conversationId = ((MainActivity) getActivity()).getConversationID(friendTag);
MainActivity activity = (MainActivity)getActivity();
activity.onConversationSelected(conversationId);
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(getArguments().getInt(
MainActivity.ARG_SECTION_NUMBER));
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case CONVERSATION_LIST_LOADER:
//Log.v(TAG, "Starting rawQuery");
String userTag = ((MainActivity)getActivity()).getUserTag();
String[] params = new String[] {
userTag
};
return new DatabaseCursorLoader(getActivity(), DatabaseHelper.QUERY_CONVERSATION_LIST, params);
default:
Log.v(TAG, "An invalid id was passed into onCreateLoader, createLoader failed!");
throw new IllegalArgumentException(
"An invalid id was passed into onCreateLoader, createLoader failed!");
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mConversationsListView.setAdapter(new ConversationListAdapter(getActivity(), cursor));
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
loader = null;
}
/**
* Allows the passing of the ID of the selected conversation back
* to the activity displaying the ConversationListFragment
*
* @author <NAME>
*/
public interface ConversationSelectedCallbacks {
public void onConversationSelected(int conversationId);
}
}
| 664bcd42f0a5eb0f635f7943c6dac35debff712d | [
"Markdown",
"Java"
] | 17 | Java | Apptimate/PingPal-Messenger-Android | da824b2accf6351d853e8ceddb21cef7784a3200 | e3c908d52321898f288ddc6664c6ba241d316d09 |
refs/heads/master | <repo_name>JamesQuinnDeveloper/MyFirstGame<file_sep>/index.js
var express = require('express');
//App setup
var app = express();
var server = app.listen(5001,function(){
console.log('listening on 5000!')
});
// Static files
app.use(express.static('public'));<file_sep>/README.md
# MyFirstGame
This is the first time I have made a game. This is a fun alien themed game. Game is all Javascript HTML/CSS.
| 30df84060d1998551d413be643f183b3337cf47f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | JamesQuinnDeveloper/MyFirstGame | a9d9b168b2ab66a2dbbbc48785487d2f1458cc2c | 041daf1dff75f0d054f93fc745ee3bc839f56496 |
refs/heads/master | <repo_name>rusted-coil/PKHeX_Raid_Plugin<file_sep>/PKHeX_Raid_Plugin/Nests/RaidTables.cs
namespace PKHeX_Raid_Plugin
{
public class RaidTables
{
public readonly RaidTemplateTable[] SwordNests =
{
new RaidTemplateTable(1676046420423018998, 1, new[]{
new RaidTemplate(236, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(66, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(532, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(559, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(67, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(533, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(106, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(107, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(560, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(534, new[]{0, 0, 0, 25, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(68, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(237, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676045320911390787, 1, new[]{
new RaidTemplate(280, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(517, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(677, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(574, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(605, new[]{5, 20, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(678, new[]{0, 0, 20, 30, 0}, 3, 2, 3, 0, 3, 1, false),
new RaidTemplate(575, new[]{0, 0, 20, 30, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(518, new[]{0, 0, 20, 30, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(576, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(338, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676044221399762576, 1, new[]{
new RaidTemplate(438, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(524, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(688, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(557, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(111, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(525, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(112, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(185, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(526, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(213, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676051917981160053, 1, new[]{
new RaidTemplate(10, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(736, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(290, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(11, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(737, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(291, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(632, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676050818469531842, 1, new[]{
new RaidTemplate(10, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(415, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(742, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(824, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(11, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(743, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(416, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(826, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676049718957903631, 1, new[]{
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(355, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(425, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(708, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(592, new[]{5, 20, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(356, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(709, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(593, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676048619446275420, 1, new[]{
new RaidTemplate(129, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(458, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(223, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(320, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(224, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(226, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(746, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676056316027672897, 1, new[]{
new RaidTemplate(833, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(422, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(320, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(834, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(847, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676055216516044686, 1, new[]{
new RaidTemplate(833, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(535, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(341, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(90, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(834, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(342, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675055760446190112, 1, new[]{
new RaidTemplate(236, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(759, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(852, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(674, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(83, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 1, 3, 0, false),
new RaidTemplate(539, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(760, new[]{0, 0, 20, 33, 22}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 33, 22}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(701, new[]{0, 0, 20, 33, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(865, new[]{0, 0, 0, 1, 1}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(853, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(870, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675056859957818323, 1, new[]{
new RaidTemplate(599, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(878, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 25, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675057959469446534, 1, new[]{
new RaidTemplate(599, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(597, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(436, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(208, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 25, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(303, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675059058981074745, 1, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 15, 0}, 2, 1, 3, 0, 3, 0, false),
new RaidTemplate(561, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 0, 20, 25, 25}, 4, 2, 4, 0, 3, 1, false),
new RaidTemplate(561, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(826, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675060158492702956, 1, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(360, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(343, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(436, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 20, 40, 15, 0}, 3, 1, 3, 1, 3, 0, false),
new RaidTemplate(561, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 0, 20, 25, 25}, 4, 2, 4, 0, 3, 1, false),
new RaidTemplate(344, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(202, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675061258004331167, 1, new[]{
new RaidTemplate(837, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(524, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(557, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(525, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(526, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675062357515959378, 1, new[]{
new RaidTemplate(50, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(749, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(290, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(529, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(339, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(208, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(340, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(51, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(530, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(750, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675063457027587589, 1, new[]{
new RaidTemplate(843, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(449, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(220, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(328, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(221, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(329, new[]{0, 0, 30, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 30, 30, 29}, 4, 2, 4, 1, 3, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 3, 0, false),
new RaidTemplate(450, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(330, new[]{0, 0, 0, 0, 35}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(844, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675064556539215800, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(607, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(554, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 1, 3, 0, false),
new RaidTemplate(758, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 2, false),
new RaidTemplate(608, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(631, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(555, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 2, 4, 0, false),
}),
new RaidTemplateTable(1675065656050844011, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(37, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 2, false),
new RaidTemplate(608, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 2, false),
new RaidTemplate(609, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(776, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677890301423150395, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(607, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(554, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 1, 3, 0, false),
new RaidTemplate(758, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 2, false),
new RaidTemplate(838, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(555, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 2, 4, 0, false),
}),
new RaidTemplateTable(1677889201911522184, 1, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(220, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(459, new[]{20, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(712, new[]{10, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(225, new[]{0, 5, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(583, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(221, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(460, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677892500446406817, 1, new[]{
new RaidTemplate(220, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(613, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(215, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 1, 3, 0, false),
new RaidTemplate(221, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(614, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(866, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(473, new[]{0, 0, 0, 15, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(873, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(461, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677891400934778606, 1, new[]{
new RaidTemplate(361, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(554, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(215, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 1, 3, 0, false),
new RaidTemplate(459, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(460, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(362, new[]{0, 0, 20, 25, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(866, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(873, new[]{0, 0, 0, 15, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(478, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(555, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 2, 4, 0, false),
}),
new RaidTemplateTable(1677894699469663239, 1, new[]{
new RaidTemplate(172, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(309, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(595, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(737, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(310, new[]{0, 0, 20, 25, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 15, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(26, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677893599958035028, 1, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(694, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 20, 25, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(871, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(877, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677896898492919661, 1, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(273, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(761, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(274, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(44, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(762, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(275, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(763, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(45, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(182, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677895798981291450, 1, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(546, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(840, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(420, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(597, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 15, 28}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(841, new[]{0, 0, 0, 0, 2}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677881505330124707, 1, new[]{
new RaidTemplate(710, new[]{10, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(708, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(710, new[]{40, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(755, new[]{15, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 5, 0, 0, 0}, 2, 1, 1, 2, 3, 0, false),
new RaidTemplate(315, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(556, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(709, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 15, 29}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(781, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(710, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 3, 4, 0, false),
}),
new RaidTemplateTable(1677880405818496496, 1, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(45, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(569, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676898541934693298, 1, new[]{
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(44, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(109, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(45, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(849, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 1, 4, 0, false),
}),
new RaidTemplateTable(1676899641446321509, 1, new[]{
new RaidTemplate(519, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(627, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(527, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(520, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(628, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(561, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676896342911436876, 1, new[]{
new RaidTemplate(821, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(278, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(177, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(425, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(845, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676897442423065087, 1, new[]{
new RaidTemplate(173, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(742, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(684, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(35, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(755, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(36, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(743, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(685, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676894143888180454, 1, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(868, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(35, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(36, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(869, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(303, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676895243399808665, 1, new[]{
new RaidTemplate(509, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(215, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(686, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(435, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(461, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(687, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(342, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(275, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676891944864924032, 1, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(509, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(859, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(633, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(828, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(861, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(634, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(635, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676893044376552243, 1, new[]{
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(328, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(610, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(714, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(782, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(329, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(783, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(611, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(612, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(330, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(776, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(784, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676907338027718986, 1, new[]{
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(840, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(782, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(885, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(714, new[]{0, 30, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 30, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(886, new[]{0, 0, 10, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(715, new[]{0, 0, 25, 35, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(783, new[]{0, 0, 25, 35, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(784, new[]{0, 0, 0, 20, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(841, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(887, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676908437539347197, 1, new[]{
new RaidTemplate(659, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(519, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(572, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(759, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(573, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(760, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679873820400064589, 1, new[]{
new RaidTemplate(819, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(831, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{20, 40, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(446, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 10, 0, 0, 0}, 2, 1, 1, 0, 3, 1, false),
new RaidTemplate(820, new[]{0, 40, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(820, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(832, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(628, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(143, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679872720888436378, 1, new[]{
new RaidTemplate(535, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(90, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(170, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(846, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(847, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(748, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679871621376808167, 1, new[]{
new RaidTemplate(422, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(98, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(341, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(593, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(834, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438842885794419703, 1, new[]{
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(854, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(355, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 20, 40, 20, 0}, 2, 1, 3, 0, 3, 0, false),
new RaidTemplate(356, new[]{0, 0, 30, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 3, 0, false),
new RaidTemplate(855, new[]{0, 0, 0, 20, 45}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(477, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(94, new[]{0, 0, 0, 0, 4}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438843985306047914, 1, new[]{
new RaidTemplate(129, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(349, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 18}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(350, new[]{0, 0, 0, 0, 2}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438845084817676125, 1, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(448, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438837388236278648, 1, new[]{
new RaidTemplate(767, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(588, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(616, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(589, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(292, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438838487747906859, 1, new[]{
new RaidTemplate(679, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(854, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(425, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(680, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 0, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(711, new[]{0, 0, 20, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(855, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 40, 29}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(681, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438839587259535070, 1, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(66, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(559, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(759, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(760, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(870, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 0, 3, 0, false),
new RaidTemplate(67, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(560, new[]{0, 0, 20, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(68, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(766, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(448, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(475, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438840686771163281, 1, new[]{
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(679, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 0, 20, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 30, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(618, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438832990189765804, 1, new[]{
new RaidTemplate(686, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(280, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(527, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438834089701394015, 1, new[]{
new RaidTemplate(557, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(438, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(837, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(185, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(874, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439833545771248589, 1, new[]{
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(339, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(622, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(623, new[]{0, 0, 20, 20, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 4}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439832446259620378, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(4, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(5, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 2, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(6, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439831346747992167, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(776, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439830247236363956, 1, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(554, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(712, new[]{10, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(361, new[]{0, 25, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(225, new[]{0, 5, 5, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 35, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(362, new[]{0, 0, 30, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 35}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(555, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 2, 4, 0, false),
}),
new RaidTemplateTable(13439829147724735745, 1, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(25, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(871, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(877, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439828048213107534, 1, new[]{
new RaidTemplate(172, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(309, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(479, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 5, 3, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 4, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 3, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 2, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 1, 4, 0, false),
}),
new RaidTemplateTable(13439826948701479323, 1, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(273, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(274, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(275, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(407, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(841, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439825849189851112, 1, new[]{
new RaidTemplate(420, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(273, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(546, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(274, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(755, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(275, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(781, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439824749678222901, 1, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(109, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(848, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(569, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(748, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439823650166594690, 1, new[]{
new RaidTemplate(177, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(821, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(278, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(225, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440790120887602934, 1, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(755, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(303, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(778, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440791220399231145, 1, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(559, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(215, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(461, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(560, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(635, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440787921864346512, 1, new[]{
new RaidTemplate(328, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(840, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(610, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(782, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(885, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(611, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(783, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(776, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(784, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(886, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(612, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(887, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440789021375974723, 1, new[]{
new RaidTemplate(659, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(519, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(819, new[]{20, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(133, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(520, new[]{0, 25, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(831, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(832, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(628, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(876, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 1, false),
new RaidTemplate(133, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(143, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440794518934115778, 1, new[]{
new RaidTemplate(132, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 25, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 25, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 25, 25, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 25, 25, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 25, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 25, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 25, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 25, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440795618445743989, 1, new[]{
new RaidTemplate(458, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(341, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(226, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(134, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440792319910859356, 1, new[]{
new RaidTemplate(686, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(527, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(196, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440793419422487567, 1, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(686, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(197, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440798916980628622, 1, new[]{
new RaidTemplate(420, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(761, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(546, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(762, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(597, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(763, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(470, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440800016492256833, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(37, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 10, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 50, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(136, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441641142887649023, 1, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(25, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(25, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(135, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441640043376020812, 1, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(712, new[]{10, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(361, new[]{0, 25, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(583, new[]{0, 5, 5, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 35, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(873, new[]{0, 0, 30, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(478, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(471, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441643341910905445, 1, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(684, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(685, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(868, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(700, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441642242399277234, 1, new[]{
new RaidTemplate(129, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(751, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(194, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(339, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(340, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(195, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441636744841136179, 1, new[]{
new RaidTemplate(458, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(223, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(320, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(224, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(226, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(4972150845118706103, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(4, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(5, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 2, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(6, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972151944630334314, 1, new[]{
new RaidTemplate(129, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(833, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(834, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972153044141962525, 1, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(273, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(274, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(275, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(407, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(841, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972145347560565048, 1, new[]{
new RaidTemplate(37, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972146447072193259, 1, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(66, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(759, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(83, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(760, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(67, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 0, 3, 0, false),
new RaidTemplate(870, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(701, new[]{0, 0, 20, 20, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(448, new[]{0, 0, 0, 20, 39}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(475, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(865, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(68, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972147546583821470, 1, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(755, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(303, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(869, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972148646095449681, 1, new[]{
new RaidTemplate(557, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(438, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(837, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(185, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(874, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972140949514052204, 1, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972142049025680415, 1, new[]{
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(679, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(618, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973141505095534989, 1, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(109, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(848, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(748, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(569, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973140405583906778, 1, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(684, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(685, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(868, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973139306072278567, 1, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(559, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(859, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(560, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(635, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973138206560650356, 1, new[]{
new RaidTemplate(177, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(821, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(278, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 35, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(561, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973137107049022145, 1, new[]{
new RaidTemplate(767, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(588, new[]{20, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{20, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(616, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(589, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(12, new[]{10, 10, 10, 10, 10}, 4, 0, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973136007537393934, 1, new[]{
new RaidTemplate(341, new[]{40, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(98, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{25, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 30, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(99, new[]{0, 10, 10, 10, 10}, 4, 1, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973134908025765723, 1, new[]{
new RaidTemplate(767, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(588, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(616, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(589, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(826, new[]{0, 0, 10, 10, 10}, 4, 2, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973133808514137512, 1, new[]{
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(339, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(622, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(623, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(844, new[]{0, 0, 0, 10, 10}, 4, 3, 4, 0, 4, 0, true),
})
};
public readonly RaidTemplateTable[] ShieldNests =
{
new RaidTemplateTable(1676046420423018998, 2, new[]{
new RaidTemplate(236, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(66, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(532, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(453, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(533, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(67, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(107, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(106, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(454, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(237, new[]{0, 0, 0, 25, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(68, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(534, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676045320911390787, 2, new[]{
new RaidTemplate(280, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(517, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(677, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(577, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(605, new[]{5, 20, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(678, new[]{0, 0, 20, 30, 0}, 3, 2, 3, 1, 3, 2, false),
new RaidTemplate(578, new[]{0, 0, 20, 30, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(518, new[]{0, 0, 20, 30, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(579, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(337, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676044221399762576, 2, new[]{
new RaidTemplate(438, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(688, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(524, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(557, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(111, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(525, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(112, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(185, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(526, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(558, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(213, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676051917981160053, 2, new[]{
new RaidTemplate(10, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(736, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(290, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(11, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(737, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(291, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(632, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676050818469531842, 2, new[]{
new RaidTemplate(10, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(415, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(742, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(824, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(11, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(743, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(416, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(826, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676049718957903631, 2, new[]{
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(355, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(425, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(708, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(592, new[]{5, 20, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(356, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(709, new[]{0, 0, 0, 40, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(593, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676048619446275420, 2, new[]{
new RaidTemplate(129, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(458, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(223, new[]{20, 30, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(320, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(224, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(226, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(746, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676056316027672897, 2, new[]{
new RaidTemplate(833, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(422, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(320, new[]{0, 20, 10, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(834, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(847, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676055216516044686, 2, new[]{
new RaidTemplate(833, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(535, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(341, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(90, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(834, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(342, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675055760446190112, 2, new[]{
new RaidTemplate(236, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(759, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(852, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(674, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(759, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(538, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(760, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(701, new[]{0, 0, 20, 30, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(760, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(853, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(870, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675056859957818323, 2, new[]{
new RaidTemplate(599, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(878, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 25, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675057959469446534, 2, new[]{
new RaidTemplate(599, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(597, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(436, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(208, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 25, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 25, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675059058981074745, 2, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{10, 30, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(77, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 1, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 15, 0}, 3, 1, 3, 0, 3, 0, false),
new RaidTemplate(561, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 0, 20, 25, 25}, 4, 2, 4, 1, 3, 2, false),
new RaidTemplate(765, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(78, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675060158492702956, 2, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(360, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(343, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(436, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 20, 40, 15, 0}, 3, 1, 3, 1, 3, 0, false),
new RaidTemplate(561, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 0, 20, 25, 25}, 4, 2, 4, 1, 3, 2, false),
new RaidTemplate(344, new[]{0, 0, 0, 10, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(202, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675061258004331167, 2, new[]{
new RaidTemplate(837, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(557, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(524, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(525, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(839, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(526, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(95, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675062357515959378, 2, new[]{
new RaidTemplate(50, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(749, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(290, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(529, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(339, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(208, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(340, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(51, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(530, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(750, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675063457027587589, 2, new[]{
new RaidTemplate(843, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(449, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(328, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(220, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(221, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 30, 20, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(329, new[]{0, 0, 30, 30, 29}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 3, 0, false),
new RaidTemplate(330, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(450, new[]{0, 0, 0, 0, 35}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(844, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675064556539215800, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(607, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 2, false),
new RaidTemplate(59, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1675065656050844011, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(58, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 2, false),
new RaidTemplate(59, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 2, false),
new RaidTemplate(324, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677890301423150395, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(757, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(607, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 2, false),
new RaidTemplate(59, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 30}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677889201911522184, 2, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(220, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(459, new[]{20, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(712, new[]{10, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(225, new[]{0, 5, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(583, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(221, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(460, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677892500446406817, 2, new[]{
new RaidTemplate(220, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(613, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(215, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 1, 3, 0, false),
new RaidTemplate(221, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(614, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(866, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(473, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(873, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(461, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677891400934778606, 2, new[]{
new RaidTemplate(361, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(225, new[]{5, 5, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(215, new[]{25, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(122, new[]{0, 30, 0, 0, 0}, 2, 1, 1, 1, 3, 0, false),
new RaidTemplate(459, new[]{0, 25, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(460, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(362, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(866, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(873, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(478, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(875, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677894699469663239, 2, new[]{
new RaidTemplate(172, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(309, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(595, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(737, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(310, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(26, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677893599958035028, 2, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(694, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(871, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(877, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677896898492919661, 2, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(270, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(761, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(271, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(44, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(762, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(272, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(763, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(45, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(182, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677895798981291450, 2, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(546, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(840, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(420, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(597, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(842, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1677881505330124707, 2, new[]{
new RaidTemplate(710, new[]{10, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(708, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(710, new[]{40, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(755, new[]{15, 35, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(710, new[]{0, 5, 0, 0, 0}, 2, 1, 1, 2, 3, 0, false),
new RaidTemplate(315, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(556, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(709, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(711, new[]{0, 0, 0, 15, 29}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(781, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(710, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 3, 4, 0, false),
}),
new RaidTemplateTable(1677880405818496496, 2, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 0, 0, 0}, 1, 1, 1, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(45, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(569, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(748, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676898541934693298, 2, new[]{
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(43, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(44, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(109, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(45, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(849, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 1, 4, 0, false),
}),
new RaidTemplateTable(1676899641446321509, 2, new[]{
new RaidTemplate(519, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(177, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(629, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(527, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(520, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(630, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(561, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676896342911436876, 2, new[]{
new RaidTemplate(821, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(278, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(177, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(425, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(845, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676897442423065087, 2, new[]{
new RaidTemplate(173, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(742, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(682, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(35, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(755, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(36, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(743, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(683, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676894143888180454, 2, new[]{
new RaidTemplate(439, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(868, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(35, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(36, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(869, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(78, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676895243399808665, 2, new[]{
new RaidTemplate(509, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(215, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(686, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(435, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(461, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(687, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(342, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(302, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676891944864924032, 2, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(509, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(859, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(629, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(828, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(861, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(630, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(248, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676893044376552243, 2, new[]{
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(610, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(328, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(714, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(704, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(329, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(611, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(705, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(330, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(612, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(780, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(706, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676907338027718986, 2, new[]{
new RaidTemplate(714, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(840, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(704, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(885, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(714, new[]{0, 30, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 30, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(886, new[]{0, 0, 10, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(715, new[]{0, 0, 25, 35, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(705, new[]{0, 0, 25, 35, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(706, new[]{0, 0, 0, 20, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(842, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(887, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1676908437539347197, 2, new[]{
new RaidTemplate(659, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(519, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(572, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(759, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(573, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(760, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679873820400064589, 2, new[]{
new RaidTemplate(819, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(831, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{20, 40, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(446, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(876, new[]{0, 10, 0, 0, 0}, 2, 1, 1, 1, 3, 2, false),
new RaidTemplate(820, new[]{0, 40, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 0, 20, 35, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(820, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(832, new[]{0, 0, 20, 25, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(660, new[]{0, 0, 0, 15, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(765, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(143, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679872720888436378, 2, new[]{
new RaidTemplate(535, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(90, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(170, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(846, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(91, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(847, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(1679871621376808167, 2, new[]{
new RaidTemplate(422, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(98, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(341, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(689, new[]{0, 0, 20, 20, 25}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 50, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(593, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(834, new[]{0, 0, 0, 0, 20}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438842885794419703, 2, new[]{
new RaidTemplate(92, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(854, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(355, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(93, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(222, new[]{0, 20, 40, 20, 0}, 3, 1, 3, 1, 3, 0, false),
new RaidTemplate(356, new[]{0, 0, 30, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(302, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 3, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 20, 45}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(864, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(477, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(94, new[]{0, 0, 0, 0, 4}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438843985306047914, 2, new[]{
new RaidTemplate(129, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(349, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 18}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(350, new[]{0, 0, 0, 0, 2}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438845084817676125, 2, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(448, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438837388236278648, 2, new[]{
new RaidTemplate(767, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(616, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(588, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(617, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(292, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438838487747906859, 2, new[]{
new RaidTemplate(679, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(854, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(425, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(680, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(222, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 1, 3, 0, false),
new RaidTemplate(426, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(302, new[]{0, 0, 20, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(855, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(864, new[]{0, 0, 0, 40, 29}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(681, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438839587259535070, 2, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(66, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(453, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(759, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(760, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(870, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 0, 3, 0, false),
new RaidTemplate(67, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(454, new[]{0, 0, 20, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(68, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(448, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(475, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438840686771163281, 2, new[]{
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(679, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 0, 20, 20}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 30, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(618, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438832990189765804, 2, new[]{
new RaidTemplate(686, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(280, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(527, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(281, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13438834089701394015, 2, new[]{
new RaidTemplate(557, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(438, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(837, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(524, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(246, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(247, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(558, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(248, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439833545771248589, 2, new[]{
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(339, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(622, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(623, new[]{0, 0, 20, 20, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 4}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439832446259620378, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(4, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(5, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 2, false),
new RaidTemplate(59, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(6, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439831346747992167, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 2, false),
}),
new RaidTemplateTable(13439830247236363956, 2, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(613, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(712, new[]{10, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(361, new[]{0, 25, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(225, new[]{0, 5, 5, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 35, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(362, new[]{0, 0, 30, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 35}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(875, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439829147724735745, 2, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(25, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(871, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(596, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(777, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(877, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439828048213107534, 2, new[]{
new RaidTemplate(172, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(309, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(595, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(25, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(479, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 5, 3, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 4, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 3, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 2, 4, 0, false),
new RaidTemplate(479, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 1, 4, 0, false),
}),
new RaidTemplateTable(13439826948701479323, 2, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(270, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(271, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(272, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(407, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(842, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439825849189851112, 2, new[]{
new RaidTemplate(420, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(270, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(546, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(271, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(755, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(272, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(781, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13439824749678222901, 2, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(109, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(848, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(569, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 2, false),
}),
new RaidTemplateTable(13439823650166594690, 2, new[]{
new RaidTemplate(177, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(821, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(278, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(225, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440790120887602934, 2, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(755, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(78, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 1, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(778, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440791220399231145, 2, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(629, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(215, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(461, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(630, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(248, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440787921864346512, 2, new[]{
new RaidTemplate(610, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(840, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(328, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(704, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(885, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(329, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(705, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(780, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(706, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(886, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(330, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(887, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440789021375974723, 2, new[]{
new RaidTemplate(659, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(519, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(819, new[]{20, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(133, new[]{10, 10, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(520, new[]{0, 25, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(831, new[]{0, 25, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(521, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(832, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(765, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(876, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 1, 4, 2, false),
new RaidTemplate(133, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(143, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440794518934115778, 2, new[]{
new RaidTemplate(132, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 25, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(132, new[]{25, 25, 0, 0, 0}, 2, 0, 1, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 25, 25, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 25, 25, 0, 0}, 3, 1, 2, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 25, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 25, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 25, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 25, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(132, new[]{0, 0, 0, 0, 25}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440795618445743989, 2, new[]{
new RaidTemplate(458, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(341, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(226, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(134, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440792319910859356, 2, new[]{
new RaidTemplate(686, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(527, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(856, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(857, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(528, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(196, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440793419422487567, 2, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(686, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(624, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(687, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(862, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(197, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440798916980628622, 2, new[]{
new RaidTemplate(420, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(761, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(546, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(762, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(597, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(421, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(763, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(547, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(470, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13440800016492256833, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(58, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(38, new[]{0, 0, 0, 10, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 50, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(136, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441641142887649023, 2, new[]{
new RaidTemplate(835, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(848, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(25, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(694, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(170, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(171, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(836, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(695, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(738, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(25, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(135, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441640043376020812, 2, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(872, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(712, new[]{10, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(361, new[]{0, 25, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(583, new[]{0, 5, 5, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 35, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(873, new[]{0, 0, 30, 20, 35}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(478, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(471, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441643341910905445, 2, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(682, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(683, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(868, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(700, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441642242399277234, 2, new[]{
new RaidTemplate(129, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(751, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(194, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(339, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(340, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(195, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(13441636744841136179, 2, new[]{
new RaidTemplate(458, new[]{68, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(223, new[]{2, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(320, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(688, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 1, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(224, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(321, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(226, new[]{0, 0, 0, 0, 10}, 4, 4, 4, 0, 4, 0, false),
}),
new RaidTemplateTable(4972150845118706103, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(4, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(5, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 2, false),
new RaidTemplate(59, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(6, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972151944630334314, 2, new[]{
new RaidTemplate(129, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(833, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(98, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(211, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(99, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(746, new[]{0, 0, 0, 20, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 40, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 1, 4, 0, false),
new RaidTemplate(834, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972153044141962525, 2, new[]{
new RaidTemplate(406, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(270, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(829, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(271, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(840, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(315, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(272, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(830, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(598, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(407, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(842, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972145347560565048, 2, new[]{
new RaidTemplate(58, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(850, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(607, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(838, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(608, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(631, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(324, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(59, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(609, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(839, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(851, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972146447072193259, 2, new[]{
new RaidTemplate(679, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(854, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(92, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(680, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(222, new[]{0, 20, 40, 10, 0}, 3, 1, 3, 1, 3, 0, false),
new RaidTemplate(93, new[]{0, 0, 20, 10, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(302, new[]{0, 0, 20, 20, 30}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(855, new[]{0, 0, 0, 20, 39}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(864, new[]{0, 0, 0, 40, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(867, new[]{0, 0, 0, 0, 1}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(94, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972147546583821470, 2, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(77, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(756, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(78, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 1, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(869, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972148646095449681, 2, new[]{
new RaidTemplate(582, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(613, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(122, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(712, new[]{10, 40, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(361, new[]{0, 25, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(225, new[]{0, 5, 5, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(713, new[]{0, 0, 35, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(362, new[]{0, 0, 30, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(584, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(866, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(875, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972140949514052204, 2, new[]{
new RaidTemplate(447, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(599, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(95, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(600, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(632, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(208, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(601, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4972142049025680415, 2, new[]{
new RaidTemplate(52, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 2, 3, 0, false),
new RaidTemplate(436, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(624, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(597, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(679, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(437, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(863, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(598, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(625, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(618, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(884, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(879, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973141505095534989, 2, new[]{
new RaidTemplate(434, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(568, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(451, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(109, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(757, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(848, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(452, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(849, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(435, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(110, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(758, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 2, false),
new RaidTemplate(569, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973140405583906778, 2, new[]{
new RaidTemplate(175, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(682, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(859, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(280, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(176, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(860, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(683, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(868, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(282, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(468, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(858, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973139306072278567, 2, new[]{
new RaidTemplate(827, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(263, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 1, 3, 0, false),
new RaidTemplate(629, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(859, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(510, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(264, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(860, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(828, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(675, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(630, new[]{0, 0, 0, 40, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(248, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(861, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973138206560650356, 2, new[]{
new RaidTemplate(177, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(163, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(821, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(278, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(12, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(822, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(164, new[]{0, 0, 20, 25, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(279, new[]{0, 0, 20, 20, 10}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(178, new[]{0, 0, 0, 20, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(701, new[]{0, 0, 0, 35, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(561, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(823, new[]{0, 0, 0, 0, 5}, 4, 4, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973137107049022145, 2, new[]{
new RaidTemplate(767, new[]{30, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(616, new[]{20, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{20, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(588, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(617, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(12, new[]{10, 10, 10, 10, 10}, 4, 0, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973136007537393934, 2, new[]{
new RaidTemplate(341, new[]{40, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(98, new[]{25, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(846, new[]{25, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(833, new[]{10, 25, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(747, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(550, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 1, 3, 0, false),
new RaidTemplate(342, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(748, new[]{0, 0, 20, 20, 15}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(771, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(130, new[]{0, 0, 0, 30, 35}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(131, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(99, new[]{0, 10, 10, 10, 10}, 4, 1, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973134908025765723, 2, new[]{
new RaidTemplate(767, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(824, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(616, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(751, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(588, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(557, new[]{0, 20, 30, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(825, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 0, 3, 0, false),
new RaidTemplate(826, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(752, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(768, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(617, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(826, new[]{0, 0, 10, 10, 10}, 4, 2, 4, 0, 4, 0, true),
}),
new RaidTemplateTable(4973133808514137512, 2, new[]{
new RaidTemplate(194, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(339, new[]{35, 0, 0, 0, 0}, 1, 0, 0, 0, 3, 0, false),
new RaidTemplate(562, new[]{20, 30, 0, 0, 0}, 1, 0, 1, 1, 3, 0, false),
new RaidTemplate(622, new[]{10, 30, 0, 0, 0}, 1, 0, 1, 0, 3, 0, false),
new RaidTemplate(536, new[]{0, 20, 20, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(195, new[]{0, 20, 40, 0, 0}, 2, 1, 2, 0, 3, 0, false),
new RaidTemplate(618, new[]{0, 0, 20, 20, 0}, 3, 2, 3, 1, 3, 0, false),
new RaidTemplate(623, new[]{0, 0, 20, 20, 20}, 4, 2, 4, 0, 3, 0, false),
new RaidTemplate(423, new[]{0, 0, 0, 20, 25}, 4, 3, 4, 1, 4, 0, false),
new RaidTemplate(537, new[]{0, 0, 0, 30, 30}, 4, 3, 4, 0, 4, 0, false),
new RaidTemplate(464, new[]{0, 0, 0, 0, 15}, 4, 4, 4, 0, 4, 0, false),
new RaidTemplate(844, new[]{0, 0, 0, 10, 10}, 4, 3, 4, 0, 4, 0, true),
})
};
public readonly RaidTemplateTable[] SwordNestsEvent =
{
new RaidTemplateTable(1721953670860364124, 1, new[]{
new RaidTemplate(840, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(840, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(868, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(868, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(837, new int[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(837, new int[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(841, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, false),
new RaidTemplate(841, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 2, 0, false),
new RaidTemplate(869, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, true),
new RaidTemplate(838, new int[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 4, 0, false),
new RaidTemplate(838, new int[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 2, 0, false),
new RaidTemplate(841, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 0, 4, 0, false),
new RaidTemplate(841, new int[]{0, 0, 20, 0, 0}, 3, 2, 2, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 3, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 4, 4, 0, true),
new RaidTemplate(839, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 0, 4, 0, false),
new RaidTemplate(839, new int[]{0, 0, 40, 0, 0}, 3, 2, 2, 0, 4, 0, true),
new RaidTemplate(841, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 0, 4, 0, false),
new RaidTemplate(841, new int[]{0, 0, 0, 20, 0}, 4, 3, 3, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 1, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 2, 4, 0, true),
new RaidTemplate(839, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 0, 4, 0, false),
new RaidTemplate(839, new int[]{0, 0, 0, 40, 0}, 4, 3, 3, 0, 4, 0, true),
new RaidTemplate(841, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 0, 4, 0, false),
new RaidTemplate(841, new int[]{0, 0, 0, 0, 20}, 5, 4, 4, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 5, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 6, 4, 0, true),
new RaidTemplate(839, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 0, 4, 0, false),
new RaidTemplate(839, new int[]{0, 0, 0, 0, 40}, 5, 4, 4, 0, 4, 0, true)
})
};
public readonly RaidTemplateTable[] ShieldNestsEvent =
{
new RaidTemplateTable(1721953670860364124, 2, new[]{
new RaidTemplate(840, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(840, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(868, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(868, new int[]{15, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(131, new int[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 4, 0, false),
new RaidTemplate(131, new int[]{20, 0, 0, 0, 0}, 1, 0, 0, 0, 2, 0, false),
new RaidTemplate(842, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, false),
new RaidTemplate(842, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 2, 0, false),
new RaidTemplate(869, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 15, 0, 0, 0}, 2, 1, 1, 0, 4, 0, true),
new RaidTemplate(131, new int[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 4, 0, false),
new RaidTemplate(131, new int[]{0, 20, 0, 0, 0}, 2, 1, 1, 0, 2, 0, false),
new RaidTemplate(842, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 0, 4, 0, false),
new RaidTemplate(842, new int[]{0, 0, 20, 0, 0}, 3, 2, 2, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 1, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 2, 4, 0, true),
new RaidTemplate(131, new int[]{0, 0, 10, 0, 0}, 3, 2, 2, 0, 4, 0, false),
new RaidTemplate(131, new int[]{0, 0, 40, 0, 0}, 3, 2, 2, 0, 4, 0, true),
new RaidTemplate(842, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 0, 4, 0, false),
new RaidTemplate(842, new int[]{0, 0, 0, 20, 0}, 4, 3, 3, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 7, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 8, 4, 0, true),
new RaidTemplate(131, new int[]{0, 0, 0, 10, 0}, 4, 3, 3, 0, 4, 0, false),
new RaidTemplate(131, new int[]{0, 0, 0, 40, 0}, 4, 3, 3, 0, 4, 0, true),
new RaidTemplate(842, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 0, 4, 0, false),
new RaidTemplate(842, new int[]{0, 0, 0, 0, 20}, 5, 4, 4, 0, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 3, 4, 0, true),
new RaidTemplate(869, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 4, 4, 0, true),
new RaidTemplate(131, new int[]{0, 0, 0, 0, 10}, 5, 4, 4, 0, 4, 0, false),
new RaidTemplate(131, new int[]{0, 0, 0, 0, 40}, 5, 4, 4, 0, 4, 0, true)
})
};
public readonly RaidTemplateTable[] CrytalNestsEvent =
{
new RaidTemplateTable(0, 1, new[]{
new RaidTemplate(782, new int[]{31, 31, 31, -1, -1, -1}, 0, false),
new RaidTemplate(246, new int[]{31, 31, 31, -1, -1, -1}, 0, false),
//new RaidTemplate(012, new int[]{31, 31, -1, -1, -1, 31}, 2, true),
})
};
}
}
| 4972c676ffbd02ca1198580b82590bf48e2b2535 | [
"C#"
] | 1 | C# | rusted-coil/PKHeX_Raid_Plugin | 9e7cb8386ebe60b3897f343827bbf95c1d9bc64b | 8ce927620bdd4373ef82af43cc8b99b93d08b5aa |
refs/heads/master | <file_sep>const server = 'http://localhost:8000/';
const requestLogs = () => {
const query = document.getElementById('query').value;
const req = new XMLHttpRequest();
req.responseType = 'json';
req.open("GET", server + 'logs', true);
req.setRequestHeader('query', query);
req.onreadystatechange = () => {
if(req.readyState === 4)
{
if(req.status === 200 || req.status == 0)
{
populateDOM(req.response);
}
}
}
req.send(null);
}
const populateDOM = (results) => {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = '';
results.forEach(result => {
const row = document.createElement('tr');
const innerHTML = `
<td>${result.from}</td>
<td>${result.to}</td>
<td>${result.productName}</td>
<td>${result.productPrice}</td>
<td>${result.transactionTime}</td>
`;
row.innerHTML = innerHTML;
searchResults.append(row);
});
}<file_sep>const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const regex = require('./regex');
const app = express();
const port = 8000;
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Methods', '*');
res.append('Access-Control-Allow-Headers', '*');
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/logs', (req, res) => {
fs.readFile('transactions.log','utf8', (err, string) => {
if (err) {
errMsg = 'Error reading the file: ' + err;
console.log(errMsg);
res.status(500).send(errMsg);
} else {
const query = req.header('query');
package = regex(string, query);
res.status(200).send(package);
}
})
})
app.post('/logs', (req, res) => {
console.log(req.body);
fs.appendFile('transactions.log', '$%' + JSON.stringify(req.body) + '%$\n', (err) => {
if (err) {
const errMsg = 'Problem writing to file: ' + err;
console.log(errMsg);
res.status(500).send(errMsg);
} else {
res.status(200).send("Transaction has been successfully logged.");
}
});
})
app.listen(port, () => {
console.log('Server is up on port ' + port)
})<file_sep>const server = 'http://localhost:8000/';
const sendLog = (logAsJSON) => {
const req = new XMLHttpRequest();
req.open("POST", server + 'logs', true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onreadystatechange = () => {
if(req.readyState === 4)
{
if(req.status === 200 || req.status == 0)
{
console.log(req.responseText);
}
}
}
req.send(JSON.stringify(logAsJSON));
} | fc99fe1e302ea76744c0f95104299ee3a7dcf62b | [
"JavaScript"
] | 3 | JavaScript | krystiano365/groceryShop | 57e75d6a56412658caf826870019d845c77f911b | 61734f2a403125480f25251027ff908be6bef3b0 |
refs/heads/master | <repo_name>no3forfuk/jsir<file_sep>/precache-manifest.c2ac24ddad5bd3a1b67f12b4fd8bbcc1.js
self.__precacheManifest = [
{
"revision": "b6216d61c03e6ce0c9aea6ca7808f7ca",
"url": "/jsir/robots.txt"
},
{
"revision": "ce6cc851b759ce59c204",
"url": "/jsir/js/chunk-vendors.2d385647.js"
},
{
"revision": "deb69425afe9041b1a4c",
"url": "/jsir/js/app.55298b18.js"
},
{
"revision": "521a5fb46f0438823cbc",
"url": "/jsir/js/about.6130274d.js"
},
{
"revision": "4a7da7b571451abe8456aeed04521f15",
"url": "/jsir/index.html"
},
{
"revision": "82b9c7a5a3f405032b1db71a25f67021",
"url": "/jsir/img/logo.82b9c7a5.png"
},
{
"revision": "a33d50da063b016852d1d139cf6e73b1",
"url": "/jsir/img/Water_1_M_Normal.a33d50da.jpg"
},
{
"revision": "deb69425afe9041b1a4c",
"url": "/jsir/css/app.b2570d08.css"
}
]; | 30e1ce20888d5f4daaf9d09df2a1030ebc5b172e | [
"JavaScript"
] | 1 | JavaScript | no3forfuk/jsir | ff48f17d68607938fe7e782e98b2d07ec74a0b5b | a2b987a8a198e75782e233d63bb9ed34eecdbe50 |
refs/heads/master | <file_sep>from classifier.gaussian_naive_bayes import GaussianNaiveBayes
from classifier.width_discrete_naive_bayes import WidthDiscreteNaiveBayes
from classifier.frequency_discrete_naive_bayes import FrequencyDiscreteNaiveBayes
from classifier.entropy_discrete_naive_bayes import EntropyDiscreteNaiveBayes
from util import validation, utils, data_providers as dp
import random
def score(data, estimator_const, est_param, k=10, cross_val=True, stratified=True):
attrs, classes = utils.horizontal_split(data)
attr_ranges = utils.attr_ranges(attrs)
unique_classes = utils.unique_classes(
classes) # it's important to recognize classes from both training and test set(whole data)
estimator = estimator_const(unique_classes, est_param, attr_ranges)
scoring = ['f1_macro', 'accuracy', 'precision_macro', 'recall_macro']
score = validation.k_fold(data, estimator, scoring, k, stratified) \
if cross_val else validation.single_split(data, estimator, scoring)
print(("mean " if cross_val else "") + f"score: {score}")
return score
def discretization_comparsion():
data_set = dp.load_wine_data()
random.shuffle(data_set)
score(data_set, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set))
score(data_set, WidthDiscreteNaiveBayes, 5)
score(data_set, FrequencyDiscreteNaiveBayes, 21)
score(data_set, GaussianNaiveBayes, None)
def on_many_datasets_comparsion():
for data_set in [dp.load_wine_data(), dp.load_glass_data(), dp.load_iris_data(), dp.load_diabetes_data()]:
random.shuffle(data_set)
score(data_set, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set))
def find_discretization_param(data_set):
max_score = 0
for i in range(1000):
score1 = score(data_set, FrequencyDiscreteNaiveBayes, i + 1)
print(i)
if max_score < score1:
max_score = score1
print(f"{max_score} {i + 1}")
def different_data_splits_comparsion():
result = []
data_set = dp.load_glass_data()
data_set_shuff = dp.load_glass_data()
random.shuffle(data_set_shuff)
for k in [2, 3, 5, 10]:
sns = score(data_set, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set), k=k, stratified=False)
ss = score(data_set, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set), k=k)
sns_shuff = score(data_set_shuff, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set), k=k,
stratified=False)
ss_shuff = score(data_set_shuff, EntropyDiscreteNaiveBayes, utils.get_entropy_intervals(data_set), k=k)
result.append([ss, sns, ss_shuff, sns_shuff])
# todo single split
for si in range(len(result[0])):
for ki in range(len(result)):
print(result[ki][si], end=' ')
print()
# find_discretization_param(dp.load_wine_data())
# discretization_comparsion()
# on_many_datasets_comparsion()
different_data_splits_comparsion()
# testowanie metod dyskretyzacji (tu można dorzucić gaussa i wybrać zbiór)
# badanie klasyfikatora na 3 różnych zbiorach
# badanie różnych podziałów danych - foldy, stratified, single split
# params
# wine, bins_count - 5
# diabetes, bins_count - 7
# iris, bins_count - 8
# glass, bins_count - 6
# wine, frequency - 21
# diabetes, frequency - 431
# iris, frequency - 3
# glass, frequency - 62
<file_sep>from sklearn.base import BaseEstimator
from util import utils
import copy
class AbstractNaiveBayes(BaseEstimator):
def get_attr_count(self, X):
return len(X[0])
def get_class_probs(self, X, y):
data = utils.merge_attrs(X, y)
class_index = utils.get_class_index(data)
result = self.get_empty_classes_dict(0)
for record in data:
class_key = record[class_index]
result[class_key] += 1
for key in result:
result[key] = result[key] / len(data)
return result
def get_empty_classes_dict(self, empty_elem):
classes = self.get_params()['classes']
result = dict()
for class_name in classes:
result[class_name] = copy.deepcopy(empty_elem)
return result
def classify_many(self, X):
y = []
for x in X:
y.append(self.classify(x))
return y
def classify(self, x):
class_x_probs = dict()
for clazz in self.get_params(False)['classes']:
class_x_probs[clazz] = self.get_class_x_prob(x, clazz)
# print(class_x_probs)
return max(class_x_probs, key=class_x_probs.get)
def get_class_x_prob(self, x, clazz):
# print(f"{self.class_probs[clazz]} | {self.get_x_class_prob(x, clazz)} | {self.get_x_prob(x)}")
return self.class_probs[clazz] * self.get_x_class_prob(x, clazz) #/ self.get_x_prob(x)
# return self.get_x_class_prob(x, clazz) # also works...
# override
def predict(self, X):
return self.classify_many(X)
<file_sep>from util import utils
from util.bin import Bin
from classifier.abstract_naive_bayes import AbstractNaiveBayes
from util.verbose_exception import VerboseException
class WidthDiscreteNaiveBayes(AbstractNaiveBayes):
def __init__(self, classes, bins_count, attr_ranges
): # library requirement is to explicity put parameters to be copied during cross-validation process
self.classes = classes
self.attr_ranges = attr_ranges
self.bins_count = bins_count
def get_attr_probs(self, X, attr_bins):
# fill counters
for i in range(self.attr_count):
for j in range(len(X)):
for l in range(len(attr_bins[i])):
min = attr_bins[i][l].min
max = attr_bins[i][l].max
val = X[j][i]
if min <= val <= max:
attr_bins[i][l].counter += 1
sizes = [len(X)] * self.attr_count # will be increased, because of smoothing
# fix all bins counters with +1 if zero (smoothing)
for i in range(self.attr_count):
for l in range(len(attr_bins[i])):
bin = attr_bins[i][l]
if bin.counter == 0:
bin.counter += 1
sizes[i] += 1
# print(attr_bins)
# fill probs
for i in range(self.attr_count):
for l in range(len(attr_bins[i])):
bin = attr_bins[i][l]
bin.prob = bin.counter / sizes[i]
return attr_bins
def get_attr_by_class_probs(self, X, y):
data = utils.merge_attrs(X, y)
class_index = utils.get_class_index(data)
result = self.get_empty_classes_dict([])
for record in data:
class_key = record[class_index]
result[class_key].append(record)
for key in result:
class_X, class_y = utils.horizontal_split(result[key])
result[key] = self.get_attr_probs(class_X, self.get_attr_bins())
return result
def get_attr_bins(self):
attr_bins = []
k = self.get_params()['bins_count']
attr_ranges = self.get_params()['attr_ranges']
for i in range(self.attr_count):
bins = []
min, max = attr_ranges[i]
width = (max - min) / k
while min < max:
bins.append(Bin(min, min + width))
min += width
attr_bins.append(bins)
return attr_bins
# override
def fit(self, X, y):
self.attr_count = self.get_attr_count(X)
self.class_probs = self.get_class_probs(X, y)
self.attr_probs = self.get_attr_probs(X, self.get_attr_bins())
self.attr_by_class_probs = self.get_attr_by_class_probs(X, y)
return self
def get_x_class_prob(self, x, clazz):
probs = self.attr_by_class_probs[clazz]
prob = self.prob(x[0], probs[0])
for i in range(1, self.attr_count):
prob_next = self.prob(x[i], probs[i])
prob *= prob_next
return prob
def get_x_prob(self, x):
prob = self.prob(x[0], self.attr_probs[0])
for i in range(1, self.attr_count):
prob *= self.prob(x[i], self.attr_probs[i])
return prob
def prob(self, x, bins):
for bin in bins:
if bin.min <= x <= bin.max:
return bin.prob
raise VerboseException(f"Value {x} is out of bins range! Learn me on full range of data.")
<file_sep>import copy
from mdlp.discretization import MDLP
from util import bin
# assumption that class is always the last attribute
def get_class_index(data):
return len(data[0]) - 1
def unique_classes(classes):
return list(set(classes))
def attr_ranges(attrs):
ranges = []
for c in range(len(attrs[0])):
ranges.append([999999, -999999])
for r in range(len(attrs)):
for c in range(len(attrs[r])):
if ranges[c][0] > attrs[r][c]:
ranges[c][0] = attrs[r][c]
if ranges[c][1] < attrs[r][c]:
ranges[c][1] = attrs[r][c]
return ranges
def horizontal_split(data):
if not data:
return [[], []]
size = len(data[0])
attrs = [record[:size - 1] for record in data]
classes_nested = [record[size - 1:] for record in data] # can flat it here instead of extra line below
classes = [item for sublist in classes_nested for item in sublist]
return [attrs, classes]
def merge_attrs(X, y):
result = []
for i in range(len(X)):
result.append(copy.deepcopy(X[i]))
result[i].append(y[i])
return result
def get_entropy_intervals(data):
X, y = horizontal_split(data)
attr_count = len(X[0])
transformer = MDLP()
X_disc = transformer.fit_transform(X, y)
attr_intervals = [list(set(transformer.cat2intervals(X_disc, i))) for i in range(attr_count)]
return [[bin.from_interval(j) for j in i] for i in attr_intervals]
<file_sep>from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_validate
from sklearn.model_selection import train_test_split
from sklearn.metrics.scorer import get_scorer
import numpy as np
from util import utils
def k_fold(data, estimator, scoring, k, stratified=True):
attrs, classes = utils.horizontal_split(data)
cv = StratifiedKFold(n_splits=k) if stratified else KFold(n_splits=k)
scores = cross_validate(estimator, attrs, classes, cv=cv, scoring=scoring)
scores_test = [scores["test_" + scoring_elem] for scoring_elem in scoring]
return np.mean(scores_test, (0, 1)) # mean by metrics then by folds
def single_split(data, estimator, scoring):
attrs, classes = utils.horizontal_split(data)
X_train, X_test, y_train, y_test = train_test_split(attrs, classes, test_size=0.4)
estimator.fit(X_train, y_train)
scorer = get_scorer(scoring)
return scorer(estimator, X_test, y_test)
<file_sep>from util import utils
import numpy as np
import scipy.stats
from classifier.abstract_naive_bayes import AbstractNaiveBayes
class GaussianNaiveBayes(AbstractNaiveBayes):
def __init__(self,
classes, plug1, plug2): # library requirement is to explicity put parameters to be copied during cross-validaion process
self.classes = classes
def get_attr_measures(self, X, y):
data = utils.merge_attrs(X, y)
first_attr_index = 0
last_attr_index = utils.get_class_index(data) - 1
result = [[] for _ in range(self.attr_count)]
for record in data:
for attr_index in range(first_attr_index, last_attr_index + 1):
result[attr_index].append(record[attr_index])
for i in range(len(result)):
attr_values = result[i]
mean = np.mean(attr_values)
std = np.std(attr_values)
result[i] = [mean, std]
return result
def get_attr_by_class_measures(self, X, y):
data = utils.merge_attrs(X, y)
class_index = utils.get_class_index(data)
result = self.get_empty_classes_dict([])
for record in data:
class_key = record[class_index]
result[class_key].append(record)
for key in result:
class_X, class_y = utils.horizontal_split(result[key])
result[key] = self.get_attr_measures(class_X, class_y)
return result
# override
def fit(self, X, y):
self.attr_count = self.get_attr_count(X)
self.class_probs = self.get_class_probs(X, y)
self.attr_measures = self.get_attr_measures(X, y)
self.attr_by_class_measures = self.get_attr_by_class_measures(X, y)
# print(f"get_attr_count: {self.attr_count}")
# print(f"class_probs: {self.class_probs}")
# print(f"classes: {self.classes}")
# print(f"get_attr_probs(data): {self.attr_probs}")
# print(f"get_attr_by_class_probs(data): {self.attr_by_class_probs}")
return self
def get_x_class_prob(self, x, clazz):
measures = self.attr_by_class_measures[clazz]
prob = self.gaussian_prob(measures[0][0], measures[0][1], x[0])
for i in range(1, self.attr_count):
prob_next = self.gaussian_prob(measures[i][0], measures[i][1], x[i])
prob *= prob_next
return prob
def get_x_prob(self, x):
prob = self.gaussian_prob(self.attr_measures[0][0], self.attr_measures[0][1], x[0])
for i in range(1, self.attr_count):
prob *= self.gaussian_prob(self.attr_measures[i][0], self.attr_measures[i][1], x[i])
return prob
def gaussian_prob(self, mean, std, x): # Gaussian Probability Density Function,
# use trick with 'f' to work on integers and get density between 0 and 1 which seems probability
# but in fact it's not needed...
f = 5
x = round(x, f) * f
mean = round(mean, f) * f
std = round(std, f) * f
prob = scipy.stats.norm.pdf(x, mean, std)
# if prob > 1:
# print(f"WARN in gaussian_prob: {prob}")
# print(f"when x: {x}, mean: {mean}, std: {std}")
# print(prob)
return prob
<file_sep>from util import utils
import numpy as np
from util.bin import Bin
from classifier.abstract_naive_bayes import AbstractNaiveBayes
from util.verbose_exception import VerboseException
class FrequencyDiscreteNaiveBayes(AbstractNaiveBayes):
def __init__(self, classes, frequency, attr_ranges
): # library requirement is to explicity put parameters to be copied during cross-validation process
self.classes = classes
self.attr_ranges = attr_ranges
self.frequency = frequency
def get_attr_probs(self, X):
attr_ranges = self.get_params()['attr_ranges']
attr_bins = []
freq = self.get_params()['frequency']
for i in range(self.attr_count):
Xsorted = np.array(X, dtype='f8')
Xsorted.view(('f8,' * self.attr_count)[:-1]).sort(order=[f'f{i}'], axis=0)
# print(Xsorted)
# mam przesortowane po kolumnie atrybutu, teraz trzeba przejść po tym i budować attr_bins
bins = []
last_val = None
min, max = attr_ranges[i]
for j in range(len(Xsorted)):
curr_val = Xsorted[j][i]
if not bins or (): # nie ma koszyka
bins.append(Bin(min, None))
bins[-1].counter += 1
elif bins[-1].counter < freq or (
last_val == curr_val): # tu po or jest zabezpieczenie przed przenoszeniem tych samych do innego koszyka
bins[-1].counter += 1
else: # trzeba zrobić kolejny koszyk
bins.append(Bin(last_val, None))
bins[-1].counter += 1
bins[-1].max = curr_val
last_val = curr_val
bins[len(bins) - 1].max = max
attr_bins.append(bins)
# print(attr_bins)
sizes = [len(X)] * self.attr_count
# increment all bins counters if zero
for i in range(self.attr_count):
for l in range(len(attr_bins[i])):
bin = attr_bins[i][l]
if bin.counter == 0:
bin.counter += 1
sizes[i] += 1
# fill probs
for i in range(self.attr_count):
for l in range(len(attr_bins[i])):
bin = attr_bins[i][l]
bin.prob = bin.counter / sizes[i]
return attr_bins
def get_attr_by_class_probs(self, X, y):
data = utils.merge_attrs(X, y)
class_index = utils.get_class_index(data)
result = self.get_empty_classes_dict([])
for record in data:
class_key = record[class_index]
result[class_key].append(record)
for key in result:
class_X, class_y = utils.horizontal_split(result[key])
result[key] = self.get_attr_probs(class_X)
return result
# override
def fit(self, X, y):
self.attr_count = self.get_attr_count(X)
self.class_probs = self.get_class_probs(X, y)
self.attr_probs = self.get_attr_probs(X)
self.attr_by_class_probs = self.get_attr_by_class_probs(X, y)
# print("attr_bins: " + self.attr_probs.__str__()) # coś za duże te prob i countery tutaj
return self
def get_x_class_prob(self, x, clazz):
probs = self.attr_by_class_probs[clazz]
# print(f"x class PROBS: {probs.__str__()}")
prob = self.prob(x[0], probs[0])
for i in range(1, self.attr_count):
prob_next = self.prob(x[i], probs[i])
# print(f"prob next: {prob_next}")
prob *= prob_next
return prob
def get_x_prob(self, x):
prob = self.prob(x[0], self.attr_probs[0])
for i in range(1, self.attr_count):
prob *= self.prob(x[i], self.attr_probs[i])
return prob
def prob(self, x, bins):
for bin in bins:
if bin.min <= x <= bin.max:
return bin.prob
raise VerboseException(f"Value {x} is out of bins range! Learn me on full range of data.")
# return 0.0001 # fixed minimum prob for values out of discretization bins range
<file_sep>import math
class Bin:
def __init__(self, min, max):
self.min = min
self.max = max
self.counter = 0
self.prob = None
def __str__(self):
return f"[min: {self.min},max: {self.max},counter: {self.counter}, prob: {self.prob}]"
def __repr__(self):
return self.__str__()
def from_interval(interval):
min = interval[0] if not interval[0] == -math.inf else -999999
max = interval[1] if not interval[1] == math.inf else 999999
return Bin(min, max)
| f2dda45e1b26103357b5ca09ee6eb30fcecdf51b | [
"Python"
] | 8 | Python | mcPear/naive-bayes | e29764910f4bd2f2687555643f4c5f88b52c13b5 | dbcf9edaef2f9bd5124a776012bdae163aaceaa0 |
refs/heads/master | <repo_name>enrq/playground-swift-uiviews<file_sep>/MyPlayground.playground/Contents.swift
import XCPlayground
import UIKit
var container = UIView(frame: CGRect(x: 0, y: 0, width: 300.0, height: 300.0))
container.backgroundColor = UIColor(red: (200.0/255.0), green: (159.0/255.0), blue: (200.0/255.0), alpha: 1.0)
XCPShowView("cont", container)
let circle = UIView(frame: CGRect(x: 0.0, y:0.0, width:50.0, height:50.0))
circle.center = container.center
circle.layer.cornerRadius = 48.0
let startingColor = UIColor(red: (253.0/255.0), green: (159.0/255.0), blue: (47.0/255.0), alpha: 1.0)
circle.backgroundColor = startingColor
container.addSubview(circle)
let square = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 4.0, height: 50.0))
square.center = container.center
square.backgroundColor = UIColor.whiteColor()
container.addSubview(square)
UIView.animateWithDuration(1.0, animations: { () -> Void in
let endingColor = UIColor(red: (255.0/255.0), green: (60.0/255.0), blue: (24.0/255.0), alpha: 1.0)
circle.backgroundColor = endingColor
let scaleTransform = CGAffineTransformMakeScale(5.0, 5.0)
circle.transform = scaleTransform
let rotationTransform = CGAffineTransformMakeRotation(3.14)
square.transform = rotationTransform
})
let textMessage = UILabel(frame: CGRect(x: 100.0, y: 265.0, width: 280.0, height: 30.0))
//textMessage.center = container.center
textMessage.text = "Hi Playground"
container.addSubview(textMessage)
| 78d77e08c8106b403fde103d5e00aed506a9cbcf | [
"Swift"
] | 1 | Swift | enrq/playground-swift-uiviews | df99d5f88e5d192d009cc0e6372168a421ceb424 | dd6fb22f50dc00e74ebdf3337aa793ee81fadb06 |
refs/heads/master | <repo_name>ztaylor54/failedxyz.github.io<file_sep>/metro/subpages/About.html
<h1>About Me</h1>
<p>I'm a junior at <a href="http://www.d125.org" target="_blank">Stevenson High School</a>. I like computer science and I make random things now and then.</p><file_sep>/metro/js/metro.js
/*
Written by <NAME>.
Metro design by Microsoft.
*/
Metro.Tile = function(_Name, _Icon, _Live, _Color) {
this.Name = _Name;
this.Icon = _Icon;
this.Live = _Live;
this.Color = _Color;
};
Metro.TileGroup = function(_Name, _Tiles) {
this.Name = _Name;
this.Tiles = _Tiles;
}
Metro.GetElements = function() {
Metro.Elements = {};
Metro.Elements.Wrapper = document.getElementById("wrapper");
Metro.Elements.TileTable = document.getElementById("tiles");
Metro.Elements.TileTableRow = document.getElementById("tilesRow");
};
Metro.OverrideRightClick = function() {
if (document.addEventListener) {
document.addEventListener("contextmenu", function(e) {
e.preventDefault();
}, false);
} else {
document.attachEvent("oncontextmenu", function() {
window.event.returnValue = false;
});
}
};
Metro.OpenApp = function(Name) {
console.log("Opening page " + Name + ".html");
$("#app-content").html("Loading page...");
$("#mask2").fadeIn("fast");
$("#wrapper").addClass("moved");
setTimeout(function() {
$("#app-page").addClass("opened");
setTimeout(function() {
$("#app-page").removeClass("closed");
}, 300);
}, 600);
$.ajax({
url: "subpages/" + Name + ".html",
dataType: "html",
data: {},
type: "GET",
success: function(content) {
$("#app-content").html(content);
console.log ("Loaded.");
},
error: function() {
$("#app-content").html("Page not found.");
}
});
};
Metro.CloseApp = function() {
$("#app-content").html("");
$("#app-page").addClass("closed");
setTimeout(function() {
$("#app-page").removeClass("opened");
setTimeout(function() {
$("#wrapper").removeClass("moved");
$("#mask2").fadeIn("fast");
}, 600);
}, 300);
};
Metro.LoadTiles = function(callback) {
Metro.Tiles = [];
$.ajax({
url: "data/tiles.json",
type: "GET",
success: function(content) {
for(var i=0;i<content.length;i++) {
var tile = new Metro.Tile();
for(asdf in content[i]) {
tile[asdf] = content[i][asdf];
}
Metro.Tiles.push(tile);
}
callback();
},
error: function() {
console.log("SHIT SOMETHING FUCKED UP");
},
});
};
Metro.LoadTileGroups = function(callback) {
Metro.TileGroups = [];
$.ajax({
url: "data/tile-groups.json",
type: "GET",
success: function(content) {
for(var i=0;i<content.length;i++) {
var tile = new Metro.TileGroup();
for(asdf in content[i]) {
tile[asdf] = content[i][asdf];
}
Metro.TileGroups.push(tile);
}
callback();
},
error: function() {
console.log("SHIT SOMETHING FUCKED UP");
}
});
};
Metro.DisplayTiles = function(callback) {
var tileN = 0;
for(var i=0;i<Metro.TileGroups.length;i++) {
var tile = Metro.TileGroups[i];
var group = document.createElement("td");
var table = document.createElement("table");
table.className = "loltable";
var trheader = document.createElement("tr");
var tdheader = document.createElement("th");
tdheader.innerHTML = tile.Name;
trheader.appendChild(tdheader);
tdheader.style.paddingBottom = "20px";
table.appendChild(trheader);
var totalRows = 3;
var rowCounter = 0;
var rows = [];
for(var j=0;j<totalRows;j++) {
rows.push(document.createElement("tr"));
}
for(var j=0;j<tile.Tiles.length;j++) {
var t = Metro.Tiles[tile.Tiles[j]];
var el = document.createElement("td");
var a = document.createElement("a");
a.setAttribute("href", "javascript:Metro.OpenApp(\""+t.Name+"\");");
a.className = "tileLink";
var tileElement = document.createElement("div");
var div = document.createElement("div");
var label = document.createElement("span");
tileElement.className = "tile";
tileElement.id = "tile"+tileN;
el.className = "tileTD";
el.setAttribute("title", t.Name);
div.className = "tileDiv";
div.style.backgroundColor = t.Color;
if (t.Icon.length>0) div.style.backgroundImage = "url(images/icons/"+t.Icon+")";
if (t.Link.length>0) {
a.setAttribute("href", t.Link);
a.setAttribute("target", "_blank");
}
div.style.backgroundSize = "cover";
label.className = "label";
label.innerHTML = t.Name;
div.appendChild(label);
tileElement.appendChild(div);
a.appendChild(tileElement);
el.appendChild(a);
rows[rowCounter%rows.length].appendChild(el);
rowCounter += 1;
tileN += 1;
}
for(var j=0;j<totalRows;j++) {
table.appendChild(rows[j]);
}
group.appendChild(table);
Metro.Elements.TileTable.appendChild(group);
}
Metro.TotalTiles = tileN;
callback();
};
Metro.InitializeMetro = function(callback) {
Metro.GetElements();
Metro.OverrideRightClick();
Metro.Theme = {};
Metro.Theme.Current = {};
Metro.Theme.Current.ImageID = Math.floor(Math.random()*16);
Metro.Theme.Current.Background = "#000000";
Metro.Theme.Current.Foreground = "#0066CC";
Metro.Elements.Wrapper.style.backgroundImage = "url('images/background/" + Metro.Theme.Current.ImageID + ".jpg')";
Metro.Elements.Wrapper.style.backgroundPosition = "center";
Metro.Elements.Wrapper.style.backgroundSize = "cover";
Metro.LoadTiles(function() {
Metro.LoadTileGroups(function() {
Metro.DisplayTiles(callback);
});
});
};
Metro.FadeInFromBlack = function() {
$("#mask").fadeOut(1250, "swing", null);
};
Metro.ShowTiles = function() {
for(var i=0;i<Metro.TotalTiles;i++) {
$("#tile"+i).animate({
left: "30px",
opacity: 1
}, 100 + i*100, "swing");
}
};
Metro.LoadCode = function(callback) {
Metro.Code = {};
$.ajax({
url: "index.html",
dataType: "html",
data: { },
type: "GET",
success: function(content) {
Metro.Code.HTML = content;
$.ajax({
url: "js/metro.js",
dataType: "html",
data: { },
type: "GET",
success: function(content) {
Metro.Code.JS = content;
$.ajax({
url: "css/metro.css",
dataType: "html",
data: { },
type: "GET",
success: function(content) {
Metro.Code.CSS = content;
callback();
},
error: function() {
console.log("wtf");
}
});
},
error: function() {
console.log("wtf");
}
});
},
error: function() {
console.log("wtf");
}
});
};
Metro.Format = function(input) {
var output = input;
if (input == "\n") output = "<br />";
if (input == "\t") output = " ";
return output;
}
Metro.TypeCode = function() {
var max = Math.max(Metro.Code.HTML.length, Math.max(Metro.Code.JS.length, Metro.Code.CSS.length));
var ind = 0;
var intval = setInterval(function() {
$("#html").append(Metro.Format(Metro.Code.HTML[ind%Metro.Code.HTML.length]));
$("#js").append(Metro.Format(Metro.Code.JS[ind%Metro.Code.JS.length]));
$("#css").append(Metro.Format(Metro.Code.CSS[ind%Metro.Code.CSS.length]));
$("#html").scrollTop($("#html").prop('scrollHeight'));
$("#js").scrollTop($("#js").prop('scrollHeight'));
$("#css").scrollTop($("#css").prop('scrollHeight'));
ind += 1;
}, 80);
};
$("#close-btn").click(function() {
Metro.CloseApp();
});
$("#profile-link, #profile tr td").click(function() {
Metro.OpenApp("Contact");
});
Metro.InitializeMetro(function() {
console.log("Done initializing.");
$('html, body').bind('touchmove', function(e){
e.preventDefault();
});
$('html, body').on('scroll', function(e){
e.preventDefault();
});
$(document).ready(function() {
Metro.FadeInFromBlack();
Metro.ShowTiles();
Metro.LoadCode(function() {
Metro.TypeCode();
});
console.dir(Metro);
});
});
<file_sep>/v1/js/dm.js
document.write("We are the Donut Mafia.");
/*
function loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
loadScript("https://parse.com/downloads/javascript/parse-1.3.5.js", function() {
console.log("Loaded.");
Parse.initialize("VvDd6NlfRFl1OabXJuCUOSc3wXWPCyKPIeOB2Q3G", "mF1dRsUvFuesztncj6vre4FGgaxvuGogLPLcYudb");
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
jQuery.getJSON("https://api.ipify.org?format=json", function(data) {
// console.log(data);
testObject.save({
ip: data.ip
}).then(function(object) {
console.log("Saved.");
});
});
});
*/
| cdc28f61a348f8e97ea451c744dbe7df2ce987dd | [
"JavaScript",
"HTML"
] | 3 | HTML | ztaylor54/failedxyz.github.io | 5058e064f078e84a9f32a1c6b081efdf2c03f148 | 38336443d6e08f9e24a0aaba05d2483745009202 |
refs/heads/master | <file_sep>#include "beep.h"
/************************************************
功能:蜂鸣器初始化及打开关闭函数
************************************************/
//==============================================================
//功能描述:初始化蜂鸣器
//参数:无
//返回:无
//==============================================================
void BEEP_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);//使能PB时钟
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; //PE8
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_ResetBits(GPIOB,GPIO_Pin_8); //默认输出低电平/蜂鸣器关闭
}
//==============================================================
//功能描述:打开蜂鸣器
//参数:无
//返回:无
//==============================================================
void BEEP_Open(void)
{
GPIO_SetBits(GPIOB,GPIO_Pin_8); //输出高电平/蜂鸣器打开
}
//==============================================================
//功能描述:关闭化蜂鸣器
//参数:无
//返回:无
//==============================================================
void BEEP_Close(void)
{
GPIO_ResetBits(GPIOB,GPIO_Pin_8); //输出低电平/蜂鸣器关闭
}
<file_sep>#include "gear.h"
void Gear_Init(void)
{
TIM2_PWM_Init(39999,35); //使用定时器2的通道3,PB10
TIM_SetCompare3(TIM2,3000);//初始化时旋转角度为0
}
void Gear_Angle(int angle)
{
int time2ch1cmp;
angle = angle + 90; //将(-90) - 90的域量化
time2ch1cmp = 1000 + angle * 4000 / 180; //到1000 - 5000的域
TIM_SetCompare3(TIM2,time2ch1cmp);
}
<file_sep>#ifndef _LQOLED_H
#define _LQOLED_H
#include "Global.h"
//汉字大小,英文数字大小
#define TYPE8X16 1
#define TYPE16X16 2
#define TYPE6X8 3
//-----------------OLED端口定义----------------
#define LCD_SCL_CLR() GPIO_ResetBits(GPIOD,GPIO_Pin_6)//PD6
#define LCD_SCL_SET() GPIO_SetBits(GPIOD,GPIO_Pin_6)
#define LCD_SDA_CLR() GPIO_ResetBits(GPIOG,GPIO_Pin_14)//PG14
#define LCD_SDA_SET() GPIO_SetBits(GPIOG,GPIO_Pin_14)
#define LCD_RST_CLR() GPIO_ResetBits(GPIOG,GPIO_Pin_15)//PG15
#define LCD_RST_SET() GPIO_SetBits(GPIOG,GPIO_Pin_15)
#define LCD_DC_CLR() GPIO_ResetBits(GPIOC,GPIO_Pin_1)//PC1
#define LCD_DC_SET() GPIO_SetBits(GPIOC,GPIO_Pin_1)
extern const u8 F8X16[];
extern const u8 nonside[]; //菱形
extern void LCD_Init(void); //LCD初始化函数
extern void LCD_CLS(void); //LCD灭屏
extern void LCD_CLS_y(char y); //灭一行
extern void LCD_CLS_line_area(u8 start_x,u8 start_y,u8 width);//从x,y开始灭宽度为width的区域
extern void LCD_P6x8Str(u8 x,u8 y,u8 *ch,const u8 *F6x8);
extern void LCD_P8x16Str(u8 x,u8 y,u8 *ch,const u8 *F8x16);
extern void LCD_P14x16Str(u8 x,u8 y,u8 ch[],const u8 *F14x16_Idx,const u8 *F14x16);
extern void LCD_P16x16Str(u8 x,u8 y,u8 *ch,const u8 *F16x16_Idx,const u8 *F16x16);
//extern void LCD_Print(u8 x, u8 y, u8 *ch);
extern void LCD_PutPixel(u8 x,u8 y);
extern void LCD_Print(u8 x, u8 y, u8 *ch,u8 char_size, u8 ascii_size);
extern void LCD_PrintInt(u8 x, u8 y, u32 ch, u8 ascii_size);
extern void LCD_Rectangle(u8 x1,u8 y1,u8 x2,u8 y2,u8 gif);
extern void Draw_BMP(u8 x,u8 y,const u8 *bmp);
extern void LCD_Fill(u8 dat);
#endif
<file_sep>#include "motor.h"
void Motor_Init()
{
TIM5_PWM_Init(199,71);
TIM_SetCompare3(TIM5,0);//³õʼÎÞPWM
TIM_SetCompare4(TIM5,0);//
}
void Motor_Left()
{
}
void Motor_Right()
{
}
<file_sep>#include "led.h"
//==============================================================
//功能描述:LED初始化函数
//参数:无
//返回:无
//==============================================================
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //GPIOB
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE); //GPIOE
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_5);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE,&GPIO_InitStructure);
GPIO_SetBits(GPIOE,GPIO_Pin_5);
}
<file_sep>#ifndef __BEEP_H
#define __BEEP_H
#include "Global.h"
void BEEP_Init(void); //初始化
void BEEP_Open(void); //打开蜂鸣器
void BEEP_Close(void); //关闭蜂鸣器
#endif
<file_sep>◆实验器材:
战舰STM32F103开发板
◆实验目的:
本实验为新建工程实验,仅供大家新建工程时参考。
◆参考资料:
电子手册:《STM32F1开发指南-库函数版本》第3.3节。
视频教程:《手把手教你学STM32》系列视频
参考书本:《原子教你玩STM32-库函数版本》
◆硬件资源:
请查看HARDWARE
◆实验现象:
暂无
◆注意事项:
该工程经修改,并添加了很多外设的源代码
----------------------------------------------------------------------------------------------------------------
<file_sep>#ifndef __KEY_H
#define __KEY_H
#include "Global.h"
#define WKUP_PRES (4) //WK_UP被按下
#define KEY2_PRES (3) //KEY2被按下
#define KEY1_PRES (2) //KEY1被按下
#define KEY0_PRES (1) //KEY0被按下
#define WK_UP GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
#define KEY0 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)
#define KEY1 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3)
#define KEY2 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2)
void KEY_Init(void);
u8 KEY_Scan(u8);
void KEY_Multi_Scan(u8 Mood, u8 *Key_Result);
#endif
<file_sep>#ifndef __GEAR_H
#define __GEAR_H
#include "Global.h"
void Gear_Init(void);
void Gear_Angle(int angle); //-90กใ- 90กใ
#endif
<file_sep>#ifndef __MOTOR_H
#define __MOTOR_H
#include "Global.h"
#define Left_IN1 PC2
#define Left_IN2 PC3
#define Right_IN1 PC4
#define Right_IN2 PC5
#endif
<file_sep>#ifndef __GLOBAL_H
#define __GLOBAL_H
#include "stm32f10x.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "led.h"
#include "key.h"
#include "timer.h"
#include "beep.h"
//#include "oled.h"
#include "gear.h"
#include "usart3.h"
#include "dht11.h"
#include "common.h"
//#include "motor.h"
#include "rfid_rcc522.h"
#endif
<file_sep>#include "timer.h"
//==============================================================
//功能描述:Timer2 Channel3初始化,PWM模式
//参数://计数器TOP值,预分频 (ARR,PSC)
//返回:无
//==============================================================
void TIM2_PWM_Init(u16 period, u16 prescaler) //计数器TOP值,预分频 (ARR,PSC)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitTypeStruct;
TIM_OCInitTypeDef TIM_OCInitTypeStruct;
//部分重映射
GPIO_PinRemapConfig(GPIO_PartialRemap2_TIM2,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //使能定时器5时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
//使能端口PB10
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //GPIOB PB10
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
//初始化TIM2
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//TIM2时钟使能
TIM_TimeBaseInitTypeStruct.TIM_Period = period;
TIM_TimeBaseInitTypeStruct.TIM_Prescaler = prescaler;
TIM_TimeBaseInitTypeStruct.TIM_CounterMode = TIM_CounterMode_Up; //上行计数
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitTypeStruct); //TIM2初始化
//初始化TIM2 Channel3 PWM2
TIM_OCInitTypeStruct.TIM_OCMode = TIM_OCMode_PWM2; //CNT>CCR有效
TIM_OCInitTypeStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitTypeStruct.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性低电平
TIM_OC3Init(TIM2,&TIM_OCInitTypeStruct);
//使能TIM2 Channel3预装载寄存器
TIM_OC3PreloadConfig(TIM2,TIM_OCPreload_Enable);
TIM_Cmd(TIM2,ENABLE);
}
//==============================================================
//功能描述:Timer3初始化,普通模式
//参数://计数器TOP值,预分频 (ARR,PSC)
//返回:无
//==============================================================
void TIM3_Normal_Init(u16 period, u16 prescaler) //计数器TOP值,预分频 (ARR,PSC)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitTypeStruct;
NVIC_InitTypeDef NVIC_InitTypeStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//TIM3时钟使能
TIM_TimeBaseInitTypeStruct.TIM_Period = period;
TIM_TimeBaseInitTypeStruct.TIM_Prescaler = prescaler;
TIM_TimeBaseInitTypeStruct.TIM_CounterMode = TIM_CounterMode_Up; //上行计数
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitTypeStruct); //TIM3初始化
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //更新中断(溢出)使能 TimeOut = (perid+1)(prescaler+1)/Tclk
NVIC_InitTypeStruct.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitTypeStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitTypeStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitTypeStruct.NVIC_IRQChannelSubPriority = 3;
NVIC_Init(&NVIC_InitTypeStruct); //优先级设置
TIM_Cmd(TIM3,ENABLE);
}
//==============================================================
//功能描述:Timer3 Channel2初始化,PWM模式
//参数://计数器TOP值,预分频 (ARR,PSC)
//返回:无
//注意:使用TIM_SetCompare2(TIM3,6000);改变占空比
//==============================================================
void TIM3_PWM_Init(u16 period, u16 prescaler) //计数器TOP值,预分频 (ARR,PSC)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitTypeStruct;
TIM_OCInitTypeDef TIM_OCInitTypeStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能定时器3时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
//部分重映射
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);
//使能端口PB5
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //GPIOB PB5
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
//初始化TIM3
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//TIM3时钟使能
TIM_TimeBaseInitTypeStruct.TIM_Period = period;
TIM_TimeBaseInitTypeStruct.TIM_Prescaler = prescaler;
TIM_TimeBaseInitTypeStruct.TIM_CounterMode = TIM_CounterMode_Up; //上行计数
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitTypeStruct); //TIM3初始化
//初始化TIM3 Channel2 PWM2
TIM_OCInitTypeStruct.TIM_OCMode = TIM_OCMode_PWM2; //CNT>CCR有效
TIM_OCInitTypeStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitTypeStruct.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性高电平
TIM_OC2Init(TIM3,&TIM_OCInitTypeStruct);
//使能TIM3 Channel2预装载寄存器
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_Cmd(TIM3,ENABLE);
}
//==============================================================
//功能描述:Timer4 Channel1-2初始化,PWM模式
//参数://计数器TOP值,预分频 (ARR,PSC)
//返回:无
//==============================================================
void TIM5_PWM_Init(u16 period, u16 prescaler) //计数器TOP值,预分频 (ARR,PSC)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitTypeStruct;
TIM_OCInitTypeDef TIM_OCInitTypeStruct;
//使能RCC时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); //使能定时器5时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
//部分重映射
//GPIO_PinRemapConfig(GPIO_Remap_TIM5,ENABLE);
//使能端口PA2 PA3
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //GPIOA PA2 PA3
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//初始化TIM5
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE);//TIM5时钟使能
TIM_TimeBaseInitTypeStruct.TIM_Period = period;
TIM_TimeBaseInitTypeStruct.TIM_Prescaler = prescaler;
TIM_TimeBaseInitTypeStruct.TIM_CounterMode = TIM_CounterMode_Up; //上行计数
TIM_TimeBaseInit(TIM5,&TIM_TimeBaseInitTypeStruct); //TIM5初始化
//初始化TIM5 Channel3/Channel4 PWM2
TIM_OCInitTypeStruct.TIM_OCMode = TIM_OCMode_PWM2; //CNT>CCR有效
TIM_OCInitTypeStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitTypeStruct.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性低电平
TIM_OC3Init(TIM5,&TIM_OCInitTypeStruct);
TIM_OC4Init(TIM5,&TIM_OCInitTypeStruct);
//使能TIM5 Channel3/Channel4 预装载寄存器
TIM_OC3PreloadConfig(TIM5,TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM5,TIM_OCPreload_Enable);
TIM_Cmd(TIM5,ENABLE);
}
//==============================================================
//功能描述:通用定时器7中断初始化
// Tout=((period+1)*(prescaler+1))/Ft us
//参数://计数器TOP值,预分频 (ARR,PSC)
//返回:无
//==============================================================
void TIM7_Int_Init(u16 period,u16 prescaler)
{
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM7, ENABLE);//TIM7时钟使能
//定时器TIM7初始化
TIM_TimeBaseStructure.TIM_Period = period; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler =prescaler; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM7, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
TIM_ITConfig(TIM7,TIM_IT_Update,ENABLE ); //使能指定的TIM7中断,允许更新中断
TIM_Cmd(TIM7,ENABLE);//开启定时器7
NVIC_InitStructure.NVIC_IRQChannel = TIM7_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//抢占优先级0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //子优先级2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
}
extern vu16 USART3_RX_STA;
//==============================================================
//功能描述:Timer7中断服务函数
//参数:无
//返回:无
//==============================================================
void TIM7_IRQHandler(void)
{
if (TIM_GetITStatus(TIM7, TIM_IT_Update) != RESET)//是更新中断
{
USART3_RX_STA|=1<<15; //标记接收完成
TIM_ClearITPendingBit(TIM7, TIM_IT_Update ); //清除TIM7更新中断标志
TIM_Cmd(TIM7, DISABLE); //关闭TIM7
}
}
//==============================================================
//功能描述:Timer3中断服务函数
//参数:无
//返回:无
//==============================================================
void TIM3_IRQHandler(void)
{
if(TIM_GetFlagStatus(TIM3,TIM_FLAG_Update))
{
/*Code*/
if(LED0_State)
LED0_Off;
else
LED0_On;
/*End*/
TIM_ClearFlag(TIM3,TIM_FLAG_Update);
}
}
<file_sep>#include "Global.h"
#include "lcd.h"
#include "math.h"
//#include "oled.h"
//#include "exfuns.h"
//#include "malloc.h"
/************************************************
ALIENTEK 战舰STM32F103开发板实验0
工程模板
注意,这是手册中的新建工程章节使用的main文件
技术支持:www.openedv.com
淘宝店铺:http://eboard.taobao.com
关注微信公众平台微信号:"正点原子",免费获取STM32资料。
广州市星翼电子科技有限公司
作者:正点原子 @ALIENTEK
************************************************/
#define TableOn11 GPIO_SetBits(GPIOA,GPIO_Pin_0)
#define TableOn12 GPIO_SetBits(GPIOA,GPIO_Pin_1)
#define TableOn13 GPIO_SetBits(GPIOA,GPIO_Pin_2)
#define TableOn14 GPIO_SetBits(GPIOA,GPIO_Pin_3)
//PA0 1 2 3
#define TableOn21 GPIO_SetBits(GPIOC,GPIO_Pin_0)
#define TableOn22 GPIO_SetBits(GPIOC,GPIO_Pin_1)
#define TableOn23 GPIO_SetBits(GPIOC,GPIO_Pin_2)
#define TableOn24 GPIO_SetBits(GPIOC,GPIO_Pin_3)
//PC0 1 2 3
#define TableOn31 GPIO_SetBits(GPIOC,GPIO_Pin_4)
#define TableOn32 GPIO_SetBits(GPIOC,GPIO_Pin_5)
#define TableOn33 GPIO_SetBits(GPIOC,GPIO_Pin_6)
#define TableOn34 GPIO_SetBits(GPIOC,GPIO_Pin_7)
//PC4 5 6 7
#define TableOn41 GPIO_SetBits(GPIOC,GPIO_Pin_8)
#define TableOn42 GPIO_SetBits(GPIOC,GPIO_Pin_9)
#define TableOn43 GPIO_SetBits(GPIOC,GPIO_Pin_10)
#define TableOn44 GPIO_SetBits(GPIOC,GPIO_Pin_11)
//PC8 9 10 11
#define TableOn51 GPIO_SetBits(GPIOC,GPIO_Pin_12)
#define TableOn52 GPIO_SetBits(GPIOC,GPIO_Pin_13)
#define TableOn53 GPIO_SetBits(GPIOG,GPIO_Pin_7)
#define TableOn54 GPIO_SetBits(GPIOG,GPIO_Pin_8)
//PC12 13 PG7 8
//分别对应各个灯的控制IO
GPIO_TypeDef* PowerOnGPIOx[21]={0,GPIOG,GPIOA,GPIOA,GPIOA,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOC,GPIOE,GPIOE,GPIOE,GPIOG};
uint16_t PowerOnPinx[21]={0,GPIO_Pin_15,GPIO_Pin_1,GPIO_Pin_2,GPIO_Pin_3,GPIO_Pin_0,GPIO_Pin_1,GPIO_Pin_2,GPIO_Pin_3,GPIO_Pin_4,GPIO_Pin_5,
GPIO_Pin_6,GPIO_Pin_7,GPIO_Pin_8,GPIO_Pin_9,GPIO_Pin_10,GPIO_Pin_11,GPIO_Pin_2,GPIO_Pin_3,GPIO_Pin_4,GPIO_Pin_13};
void ZutaiGPIO_Init(void)
{
u8 i;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //GPIOA
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //GPIOB
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE); //GPIOC
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOG,ENABLE); //GPIOG
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE); //GPIOG
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
// GPIO_Init(GPIOC,&GPIO_InitStructure);
// GPIO_ResetBits(GPIOC,GPIO_Pin_0);
for(i=1;i<=20;i++)
{
GPIO_InitStructure.GPIO_Pin = PowerOnPinx[i];
GPIO_Init(PowerOnGPIOx[i],&GPIO_InitStructure);
GPIO_ResetBits(PowerOnGPIOx[i],PowerOnPinx[i]);
delay_ms(10);
}
}
int main()
{
u32 key,port = 0,port_temp = 0;
u32 TableStatus=0, TableStatus_pre = 0;
int i=1,j=0;
u8 port_str[6] = {'1','\0'};
uart_init(9600);
usart3_init(115200); //初始化串口3
//DHT11_Init();
delay_init();
//LCD_Init();
LCD_DisplayOn();
//LED_Init();
ZutaiGPIO_Init();
//LCD_Init();
//LCD_DisplayOff();
//KEY_Init();
RC522_Init(); //初始化射频卡模块
POINT_COLOR=RED;//设置字体为红色
LCD_ShowString(30,50,200,16,16,"WarShip STM32");
LCD_ShowString(30,70,200,16,16,"TOUCH TEST");
LCD_ShowString(30,90,200,16,16,"ATOM@ALIENTEK");
LCD_ShowString(30,110,200,16,16,"2015/1/15");
while(1)
{
///刷卡检测进程
RC522_Handel();
delay_ms(300);
///获取Table数据
u3_printf("Read\r\n");
delay_ms(300); //等待数据返回
///解析接收到的数据
if(USART3_RX_STA&1<<15)
{
i = 0;
j = 0;
while(USART3_RX_BUF[i]!='\0')
{
i++;
}
TableStatus = 0;
while(i > 0)
{
if(USART3_RX_BUF[0]=='O')
{
TableStatus=TableStatus_pre;
USART3_RX_BUF[0]=USART3_RX_BUF[1]=USART3_RX_BUF[2]=USART3_RX_BUF[3]=USART3_RX_BUF[4]='\0';
break;
}
i--;
TableStatus = TableStatus + (USART3_RX_BUF[j]-0x30) * pow(10,i);
USART3_RX_BUF[j++] = '\0';
}
USART3_RX_STA = 0;
LCD_ShowxNum(1,1,TableStatus,8,16,(1<<7));
}
///执行电力操作
if(TableStatus!=TableStatus_pre)
{
for(i=1; i<=20; i++)
{
if(TableStatus&(1<<i))
{
//Table On
LED0_On;
//GPIO_SetBits(GPIOC,GPIO_Pin_0);
GPIO_SetBits(PowerOnGPIOx[i],PowerOnPinx[i]);
}
else
{
//Table Off
LED1_On;
GPIO_ResetBits(PowerOnGPIOx[i],PowerOnPinx[i]);
}
}
TableStatus_pre = TableStatus;
}
///按键
key = KEY_Scan(0);
if(key)
{
switch(key)
{
case WKUP_PRES:
{
//此处写入WKUP被按下时需要处理内容
break;
}
case KEY0_PRES:
{
GPIO_SetBits(GPIOC,GPIO_Pin_12);
//此处写入KEY0被按下时需要处理内容
//printf("%s","A0F016475\r");
break;
}
case KEY1_PRES:
{
//此处写入KEY1被按下时需要处理内容
port+=1;
break;
}
case KEY2_PRES:
{
//此处写入KEY2被按下时需要处理内容
port+=2;
break;
}
}//switch(key)
}//if(key)
}
}
<file_sep>#include "Global.h"
#define DHT11_GPIOx GPIOA
#define DHT11_Pin_x GPIO_Pin_1
u8 g_TRHData[5] = {0x00,0x00,0x00,0x00,0x00}; //存放温湿度数据
//摘掉P10跳线帽
void dht11_gpio_Init()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//使能PA时钟
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = DHT11_Pin_x; //PA1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(DHT11_GPIOx,&GPIO_InitStructure);
GPIO_SetBits(DHT11_GPIOx,DHT11_Pin_x); //默认输出高电平,等待送入开启信号
}
void dht11_gpio_outhigh()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = DHT11_Pin_x; //PA1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(DHT11_GPIOx,&GPIO_InitStructure);
GPIO_SetBits(DHT11_GPIOx,DHT11_Pin_x); //默认输出高电平,等待送入开启信号
}
void dht11_gpio_outlow()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = DHT11_Pin_x; //PA1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(DHT11_GPIOx,&GPIO_InitStructure);
GPIO_ResetBits(DHT11_GPIOx,DHT11_Pin_x); //默认输出高电平,等待送入开启信号
}
void dht11_gpio_inhigh()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = DHT11_Pin_x; //PA1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(DHT11_GPIOx,&GPIO_InitStructure);
}
void dht11_gpio_inlow()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //推挽输出模式
GPIO_InitStructure.GPIO_Pin = DHT11_Pin_x; //PA1
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(DHT11_GPIOx,&GPIO_InitStructure);
}
void DHT11_Init()
{
delay_init();
dht11_gpio_Init();
}
int DHT11_Read()
{
int i,j,read_state = 0;
DHT11_OUT_LOW;
delay_ms(25);
DHT11_OUT_HIGH;
delay_us(30);
DHT11_IN_HIGH;
while(DHT11_IN_LEVEL);
if(!DHT11_IN_LEVEL)
{
while(!DHT11_IN_LEVEL);
while(DHT11_IN_LEVEL);
for(i = 0; i < 5; i++)
{
g_TRHData[i] = 0;
for(j = 7; j >= 0; j--)
{
while(DHT11_IN_LEVEL);
while(!DHT11_IN_LEVEL);
delay_us(50);
if(!DHT11_IN_LEVEL)
{
g_TRHData[i] &= ~(1<<j);
}
else
{
g_TRHData[i] |= (1<<j);
}
}
}
while(!DHT11_IN_LEVEL);
i = g_TRHData[0] + g_TRHData[1] + g_TRHData[2] + g_TRHData[3];
if(i == g_TRHData[4])
{
read_state = 1;
}
}
return read_state;
}
//调用间隔应大于2s
float DHT11_Get_T(void)
{
if(DHT11_Read())
{
if(0 != g_TRHData[4])
{
return g_TRHData[2]+g_TRHData[3]/10;
}
}
return 0;
}
//应该与get_T一同使用
float DHT11_Get_RH(void)
{
if(0 != g_TRHData[4])
{
return 0;
}
return g_TRHData[0];
}
<file_sep>#ifndef __DHT11_H
#define __DHT11_H
#include "Global.h"
#define DHT11_OUT
#define DHT11_OUT_HIGH dht11_gpio_outhigh()
#define DHT11_OUT_LOW dht11_gpio_outlow()
#define DHT11_IN_HIGH dht11_gpio_inhigh()
#define DHT11_IN_LOW dht11_gpio_inlow()
#define DHT11_IN_LEVEL GPIO_ReadInputDataBit(DHT11_GPIOx,DHT11_Pin_x)
void DHT11_Init(void);
int DHT11_Read(void);
extern u8 g_TRHData[5];
#endif
<file_sep>#ifndef __TIMER_H
#define __TIMER_H
#include "Global.h"
void TIM3_Normal_Init(u16 period, u16 prescaler); //计数器TOP值,预分频 (ARR,PSC) //TimeOut = (perid+1)(prescaler+1)/Tclk
void TIM3_PWM_Init(u16 period, u16 prescaler); //计数器TOP值,预分频 (ARR,PSC)
void TIM2_PWM_Init(u16 period, u16 prescaler); //计数器TOP值,预分频 (ARR,PSC)
void TIM7_Int_Init(u16 period, u16 prescaler);
void TIM5_PWM_Init(u16 period, u16 prescaler); //计数器TOP值,预分频 (ARR,PSC)
#endif
<file_sep>#include "key.h"
//==============================================================
//功能描述:按键初始化,使用前必须进行初始化
//参数:无
//返回:无
//==============================================================
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
delay_init(); //使用按键时需要初始化延迟函数
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE|RCC_APB2Periph_GPIOA,ENABLE);//使能PE/PA时钟
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //下拉输入模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; //PA0
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4; //PE2/PE3/PE4
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz
GPIO_Init(GPIOE,&GPIO_InitStructure);
}
//==============================================================
//功能描述:当需要使用按键时,将此程序复制到main函数中使用
//参数:Mood:/1-支持连续按下检测 /0-不支持连续按下检测
//返回:u8类型,返回各按键状态
//==============================================================
u8 KEY_Scan(u8 Mood) //1-支持连续按下 /0-不支持连续扫描
{
static u8 key_up = 1; //记录上次按键状态
if(Mood) key_up = 1; //支持连续按下
if(key_up && (WK_UP == 1 || KEY0 == 0 || KEY1 == 0 || KEY2 == 0))
{
key_up = 0;
delay_ms(10);
if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 1) return WKUP_PRES; //返回WKUP键按下
else if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2) == 0) return KEY2_PRES; //返回KEY2键按下
else if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3) == 0) return KEY1_PRES; //返回KEY1键按下
else if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) == 0) return KEY0_PRES; //返回KEY0键按下
}
else if(WK_UP == 0 && KEY0 == 1 && KEY1 == 1 && KEY2 == 1) key_up = 1;
return 0;
}
void KEY_Multi_Scan(u8 Mood, u8 *Key_Result) //1-支持连续按下 /0-不支持连续扫描
{
static u8 key_up = 1; //记录上次按键状态
if(Mood) key_up = 1; //支持连续按下
if(key_up)
{
if(WK_UP == 1 || KEY0 == 0 || KEY1 == 0 || KEY2 == 0)
{
Key_Result[0] = 1;
key_up = 0; //只能进入一次
delay_ms(10);
if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == 1) Key_Result[WKUP_PRES] = 1; //返回WKUP键按下
else Key_Result[WKUP_PRES] = 0;
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_2) == 0) Key_Result[KEY2_PRES] = 1; //返回KEY2键按下
else Key_Result[KEY2_PRES] = 0;
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_3) == 0) Key_Result[KEY1_PRES] = 1; //返回KEY1键按下
else Key_Result[KEY1_PRES] = 0;
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4) == 0) Key_Result[KEY0_PRES] = 1; //返回KEY0键按下
else Key_Result[KEY0_PRES] = 0;
}
}
else
{
Key_Result[0] = 0;
if(WK_UP == 0 && KEY0 == 1 && KEY1 == 1 && KEY2 == 1)
{
key_up = 1; //所有按键释放时key_up复位,等待下次按键按下
}
}
}
//==============================================================
//功能描述:当需要使用按键时,将此程序复制到main函数中使用
//参数:需要在main中定义u8 key
//返回:无
//==============================================================
int KEY_main(void)
{
u8 key;
while(1)
{
key = KEY_Scan(0);
if(key)
{
switch(key)
{
case WKUP_PRES:
{
//此处写入WKUP被按下时需要处理内容
break;
}
case KEY0_PRES:
{
//此处写入KEY0被按下时需要处理内容
break;
}
case KEY1_PRES:
{
//此处写入KEY1被按下时需要处理内容
}
case KEY2_PRES:
{
//此处写入KEY2被按下时需要处理内容
break;
}
}//switch(key)
}//if(key)
}//while(1)
}
<file_sep>#ifndef __LED_H
#define __LED_H
#include "Global.h"
#define LED0_State !GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_5)
#define LED1_State !GPIO_ReadOutputDataBit(GPIOE,GPIO_Pin_5)
#define LED0_On GPIO_ResetBits(GPIOB,GPIO_Pin_5)
#define LED1_On GPIO_ResetBits(GPIOE,GPIO_Pin_5)
#define LED0_Off GPIO_SetBits(GPIOB,GPIO_Pin_5)
#define LED1_Off GPIO_SetBits(GPIOE,GPIO_Pin_5)
void LED_Init(void);
#endif
| 6530ec12cfce6473cab54ca88dae08a15dcd53e6 | [
"C",
"Text"
] | 18 | C | Forever1715/ES-0MyTemplate | 6cb8a39d9517df09073b2f68b51b055e16e8511d | 917fb488d27bb94dd11853631fdeec82169c9cca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.